Generate a new entry for a singular piece of data within an array

I am working on a matchmaking system where two players of the same level are matched and joined in one array. My goal is to include a second data in the array for players who do not have a match.

Example: EntryID: “15”, player: ”testing11”, level: ”3”
         EntryID: ”nm”, player: ”nm”, level: ”nm”;

In the example provided, when a player does not have a match, another data point with "nm" meaning no match should be included.

I have attached an image depicting my goal for better understanding of the issue and objective. Thank you.

https://i.sstatic.net/FIVmL.png

Script:

let ajaxResult = []; // the pushed data will be saved here
let save_method;
let table;
let base_url = "<?php echo base_url();?>";
let result = [];
var html = "";

// This is where the same level will be matched
const combine = (source) => {
    return source.reduce((acc, curr) => {
        if (acc[curr.level]) {
            const levelArr = acc[curr.level];
            const last = levelArr[levelArr.length - 1];
            if (last.length === 2) {
                levelArr.push([curr])
            } else {
                last.push(curr)
            }
        } else {
            acc[curr.level] = [
                [curr]
            ];
        }
        return acc;
    }, {})
};

// I am removing duplicates here. Test 1 vs Test 1 should not be possible
function removeDuplicates(result) {
    return Object.values(result.reduce((acc, curr) => { 
        acc[curr.player] = acc[curr.player] || curr;
        return acc;
    }, {}))
}

const uniquePlayers = removeDuplicates(result);

$(document).ready(function() {
    //datatables
    table = $("#entry_list1").DataTable({
        processing: false,
        serverSide: true,
        order: [],
        searching: false,
        paging: false,
        info: false,

        ajax: {
            url: "<?php echo site_url('controller/fetch_players')?>",
            type: "POST",
            async: true,
            dataType: "json",
            success: function(data) {
                result = combine(removeDuplicates(data.data2));
                var keys = Object.keys(result)

                // I am creating a textbox depending on the matches above so that I can insert it into the DB. My goal here is to create a textbox for my "no match" player, as the current code only creates textboxes for matched players.
                for (var i = 0; i < keys.length; i++) {
                    result[keys[i]].forEach(function(val) {
                        val.forEach(function(value, index) {
                            var entryIDs = index == 0 ? "entryIDM[]" : "entryIDW[]";
                            var players = index == 0 ? "playerM[]" : "playerW[]";
                            var levels = index == 0 ? "levelM[]" : "levelW[]";
                            html += `<input type="text" name="${entryIDs}" value="${value.entryID}">
                             <input type="text" name="${players}" value="${value.player}">
                             <input type="text" name="${levels}" value="${value.level}">`;
                        })
                    })
                }
                document.getElementById("result").innerHTML = html;
            },
        },

        "columnDefs": [{
                "targets": [0], //first column
                "orderable": false, //set not orderable
            },
            {
                "targets": [-1], //last column
                "orderable": false, //set not orderable
            },

        ],
    });
});

JSON.stringify:

{"draw":"1","recordsTotal":5,"recordsFiltered":5,"data":[["15","testing11","3"],["13","testing8","1"],["4","testing4","2"],["3","testing3","2"],["1","testing1","1"]],"data2":[{"entryID":"15","player":"testing11","level":"3"},{"entryID":"13","player":"testing8","level":"1"},{"entryID":"4","player":"testing4","level":"2"},{"entryID":"3","player":"testing3","level":"2"},{"entryID":"1","player":"testing1","level":"1"}]}

Answer №1

If you only want to input data for nm, you can verify the length of the JSON Array to see if it is equal to 1. If it is, then it indicates that only one match has been found, allowing you to add additional matches with nm values inside val.forEach(...

Sample Code:

// Sample code for demonstration purposes....
var data = {
  "data2": [{
    "entryID": "15",
    "player": "testing11",
    "level": "3"
  }, {
    "entryID": "13",
    "player": "testing8",
    "level": "1"
  }, {
    "entryID": "4",
    "player": "testing4",
    "level": "2"
  }, {
    "entryID": "3",
    "player": "testing3",
    "level": "2"
  }, {
    "entryID": "1",
    "player": "testing1",
    "level": "1"
  }, {
    "entryID": "5",
    "player": "testing5",
    "level": "5"
  }]
}

const combine = (source) => {
  return source.reduce((acc, curr) => {
    if (acc[curr.level]) {
      const levelArr = acc[curr.level];
      const last = levelArr[levelArr.length - 1];
      if (last.length === 2) {
        levelArr.push([curr])
      } else {
        last.push(curr)
      }
    } else {
      acc[curr.level] = [
        [curr]
      ];
    }
    return acc;
  }, {})
};

function removeDuplicates(result) {
  return Object.values(result.reduce((acc, curr) => {
    acc[curr.player] = acc[curr.player] || curr;
    return acc;
  }, {}))
}

result = combine(removeDuplicates(data.data2));
var keys = Object.keys(result)
var html = ""
for (var i = 0; i < keys.length; i++) {
  result[keys[i]].forEach(function(val) {
    var length_ = val.length; //length of the json aray inside obj
    val.forEach(function(value, index) {

      var entryIDs = index == 0 ? "entryIDM[]" : "entryIDW[]"
      var players = index == 0 ? "playerM[]" : "playerW[]"
      var levels = index == 0 ? "levelM[]" : "levelW[]"
      html += `<input type="text" name="${entryIDs}" value="${value.entryID}"> 
                 <input type="text" name="${players}" value="${value.player}">
                 <input type="text" name="${levels}" value="${value.level}">`

      //if length is only one
      if (length_ == 1) {
        //just add inputs with nm..
        html += `<input type="text" name="entryIDW[]" value="nm"> <input type="text" name="playerW[]" value="nm"><input type="text" name="levelW[]" value="nm">`
      }

    })
  })
}
document.getElementById("result").innerHTML = html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my Google Chrome extension to only allow me to open 25 tabs instead of more?

Having a frustrating issue with my code that is causing problems when used as a Chrome Extension. Despite checking and confirming that the code should work correctly, it seems to stop opening pages after tab 25. I have verified that the code attempts to o ...

Display new information within a div element seamlessly without refreshing the page

Just a heads-up, I'm new to HTML development... Currently working on a website using Bootstrap. There are some buttons on the left side shown in the screenshot, and my goal is to update the content on the right without having to reload the entire pag ...

Show off a font-awesome icon overlapping another image

My task involves fetching image source from a JSON file and then displaying it on an HTML page. https://i.sstatic.net/coOaU.png I also need to overlay a Font Awesome icon on top of the image as shown below: https://i.sstatic.net/nbrLk.png https://i.sst ...

The MUI date picker does not display dates earlier than 1900

I am in need of a datepicker that allows users to select dates from the 1850s, however, the mui datepicker only starts from the 1900s. To demonstrate this issue, I have provided a sample code in this codesandbox I am utilizing mui in the remainder of my ...

The Power of Symfony Combined with jQuery's Data Handling Function

My app features an ajax navigation system. Each ajax link is given the class ajax, and the page it should load is stored in an aurl attribute, as shown below: <a class="ajax" aurl="/user/posts/3/edit">Edit Post</a> The element's aurl is ...

PHP unable to properly receive accented characters sent via Ajax requests

Recently, I developed an Ajax script that fetches data from MySQL and returns it to PHP upon changing a select option: $country = $_POST['country']; $sql = "SELECT id,name FROM regions WHERE idcountry='$country' ORDER BY name ASC"; $re ...

Click on a new tab to enable printing options for the page

I am looking to enhance the print page functionality on my website. Currently, when the print icon in the footer is clicked, it opens the printer dialog box directly. I would like to change this behavior so that when the Print icon is clicked, the contents ...

"Implementing conditional rendering to hide the Footer component on specific pages in a React application

Is there a way to conceal the footer component on specific pages? app.js <div className="App"> <Header setShowMenu={setShowMenu} /> {showMenu ? <Menu navigateTo={navigateTo} setShowMenu={setShowMenu} /> : null} <Main na ...

What is the best way to send a value through an AJAX request?

My ajax update function is not working in the code below. How can I solve this issue? The edit method in my code is functioning properly. For example, the value is being passed in this code snippet: var name = row.find(".ContactPersonName").find("span"). ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

There was a TypeError that was not caught in the promise, stating that the function window.showOpenFilePicker is not valid

Encountering TypeError with File System Web API While experimenting with the File System Web API, I keep receiving a TypeError stating Uncaught (in promise) TypeError: window.showOpenFilePicker is not a function. I am unsure of what is causing this issue. ...

Tips for narrowing down table searches to only rows containing certain text within a column

Currently, I have a function that allows me to search through my table: //search field for table $("#search_field").keyup(function() { var value = this.value; $("#menu_table").find("tr").each(function(index) { if (index === 0) return; var id = $( ...

When the button is clicked, the JavaScript function is not being executed

I'm having a strange issue with my second button not working as expected. Despite appearing to be straightforward, the "Reset" button does not seem to be triggering the clear() function. Within the HTML code, I have two buttons set up to interact wit ...

A method for performing precise division on numbers in JavaScript, allowing for a specific precision level (such as 28 decimal places)

I've searched extensively for a library that can handle division operations with more than 19 decimal places, but to no avail. Despite trying popular libraries like exact-math, decimal.js, and bignumber.js, I have not found a solution. How would you ...

Using Nuxt.js to import custom NPM packages on a global scale

The installation process for Nuxt's plugins/modules system can be quite intricate. Despite attempting to follow various suggestions, I have struggled to accomplish a seemingly simple task. After installing the NPM package csv-parse (which can be found ...

I am facing a challenge with AngularJS where I am unable to navigate between pages using the

I'm having issues with my route file app.js. Whenever I click on any link or button, it redirects me to books.html. What could be the mistake I'm making? var myApp = angular.module('myApp', ['ngRoute']); myApp.config([&apo ...

Issue encountered when attempting to make a global call to an asynchronous function: "The use of 'await' is restricted to async functions and the top level bodies of modules."

As I embark on solving this issue, I want to point out that while there are similar questions on SO based on the title, upon close examination, they seem more intricate than my specific situation. The explanations provided in those threads do not quite ali ...

Using Props with jQuery in React Components: A Comprehensive Guide

I trust you comprehend this straightforward example. I attempted to modify the background color of my HTML element during initial rendering by managing it in a React Component with a touch of jQuery assistance. Here is the code within my React Component ...

Enum-Based Object Indexing

The structure I am currently working with is as follows; import data from "../data.min.json"; export enum TileType { tree = 'tree', rock = 'rock' } interface MapTile { walkable: boolean; positions: number[][]; } exp ...

Tips on aligning a span element at the center of an image without losing its mouseover

<div class="pic"> <img src="image.jpg" height="250"/> <span class="text" style="display:none">text here</span> </div> <scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </scrip ...