Creating keys for my console.log data and appending it to html in order to display console log results in textboxes

I am currently developing a matching system for Player vs. Player battles and I need to ensure that the keys are appended correctly to my div element. Previously, I have successfully used append with keys before. Below is the code snippet:


            const source = [{
                    entryID: 1,
                    entryName: 'player1',
                    weight: 1900,
                },
                {
                    entryID: 2,
                    entryName: 'player2',
                    weight: 1900,
                },
                ...
            ];

            // Function to combine based on weight
            const combine = (source) => {
                return source.reduce((acc, curr) => {
                    if (acc[curr.weight]) {
                        const levelArr = acc[curr.weight];
                        const last = levelArr[levelArr.length - 1];
                        if (last.length === 2) {
                            levelArr.push([curr]);
                        } else {
                            last.push(curr);
                        }
                    } else {
                        acc[curr.weight] = [
                            [curr]
                        ];
                    }
                    return acc;
                }, {});
            };

            var result = combine(source);
            var html = "";
            var keys = Object.keys(result);

            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 handlers = index == 0 ? "handlerM[]" : "handlerW[]";
                        var weights = index == 0 ? "weightM[]" : "weightW[]";

                        html += `<input type="text" name="${entryIDs}" value="${value.entryID}"> 
                                 <input type="text" name="${handlers}" value="${value.entryName}">
                                 <input type="text" name="${weights}" value="${value.weight}">`;
                    });
                });
            }

            document.getElementById("result").innerHTML = html;

            console.log(result);
        

After using the newCombine function, I now need assistance on how to create keys and append these results as textboxes. Please see the following image for reference: https://i.stack.imgur.com/tQ6WS.png

The provided code snippet works well when combining two data entries with the same weight. However, I'm facing challenges in applying this logic to cases where there is less than or greater than equal to a 15-weight difference between entries. Any help would be greatly appreciated. Thank you!

HTML

<div id="appendhere"></div>

AJAX


        // Using Ajax to fetch data and perform operations
        $(document).ready(function() {
            var entry_list = $('#entry_list1').DataTable({
                "ajax": {
                    "url": "<?php echo site_url('report/controlget')?>",
                    "type": "get",
                    success: function(data) {
                        const source = data;
                        const a = newCombine(source, 15);
                        
                        console.log(a);
                        
                        // How do I append the keys here?
                    }
                }
            });
        });
    

Answer №1

Introduction

In this explanation, I will focus on a solution that is versatile and can be used in various ways without relying on console or div-related functions. You have the flexibility to leverage the outcome however you see fit, whether it's integrating it into a div element or displaying it in the console.

Issue at Hand

The task at hand involves grouping items based on a specific criterion, where the weight difference between them does not exceed a certain threshold, such as 15 units.

Acknowledging Imperfection

Let's illustrate this with an example involving weights like 1900, 1910, and 1920. It's impossible to form a single group consisting of (1900, 1910, and 1920) because the difference between 1920 and 1900 exceeds 15, which is 20 units.

Possible groupings could include (1900, 1910), (1920), or (1900), (1910, 1920).

An Imperfect Yet Viable Approach

const source = [{
    entryID: 1,
    entryName: 'player1',
    weight: 1900,
    
  },
  // Other data entries
];

let groups = [];

// Logic for grouping elements based on weight criteria

document.getElementById("foo").innerText = JSON.stringify(groups);
<div id="foo"></div>

We iterate through the elements and assign each one to the first matching group. If no suitable group is found, we create a new group for that element.

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

Node.js removes leading zeroes from dates

I am looking to generate a string with the current date and time in the format: "2021-06-02 09:37:38" const today = `${new Date().toLocaleDateString('sv-se')} ${new Date().toLocaleTimeString('sv-se')}`; console.log(today); ...

Error: Expecting only one React element child to be passed into React.Children.only() function

I am encountering an issue while attempting to construct a web table using the antd library. The exact error message reads: "react.development.js:1251 Uncaught Error: React.Children.only expected to receive a single React element child". I have been stru ...

Can anyone recommend a user-friendly JavaScript dialog box compatible with jQuery that is mobile-responsive?

Mobile browsers. Using Jquery dialog alert box. Avoiding the use of alert() due to its unattractive appearance in web browsers. In the process of creating a website for both mobile and web platforms, seeking a dialog box that is compatible with both. ...

Setting a default value for Autocomplete in MaterialUI and React.js

Is there a way to set a default value for an Autocomplete TextField component from Material UI in React.js? I want to load a pre-populated value from the user's profile that can then be changed by selecting another option from a list. Check out my co ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

Unable to invoke requestPointerLock() function within Vue.js component

Incorporating the requestPointerLock() method within a Vue.js component has posed some challenges for me. In the scenario where the pointerShouldLock data property of my component is set to true, I intend for the pointer to be locked during the beforeUpdat ...

hyperlink to choose a specific option from a drop-down menu

The challenge I am currently working on involves page1.html <a href="/foo"></a> foo.html <select ng-model="ctrl.listvalues"> <option id="{{item.value}}" ng-repeat="item" in ctrl.availableValues" value="{{item.value}}">item.di ...

Ways to emphasize the contrast between two texts using CSS

One method to highlight specific parts of text using CSS can be found in this script: span.highlight { background-color: #B4D5FF; } However, what if we want to highlight the differences between two strings? Take for example these two strings: this ...

Designing an intricate layout with the help of Bootstrap-Vue

After exploring the Vue-Bootstrap panel in my previous question, I implemented the following code snippet to generate a panel: <b-card no-body class="mb-1"> <b-card-header header-tag="header" class="p-1" role="tab"> <b-button b ...

Cart cannot function as a constructor

I'm currently learning express.js and trying to implement a shopping cart/session functionality into my project. Below is the code I have written so far, with a question at the end. Here is my cart.js: // Ensure that the file is required correctly b ...

Get a Blob as a PNG File

Hope you had a wonderful Christmas holiday! Just to clarify, I am new to JS and may make some unconventional attempts in trying to download my Blob in PNG format. I am facing an issue with exporting all the visual content of a DIV in either PDF or image ...

Best Practices for Installing Webpack in a Client/Server Folder Structure

Working on a React Nodejs web application and in the process of figuring out how to bundle the frontend using webpack. This is how my project's structured: Where exactly do I need to install webpack and configure webpack.config.js? I've noticed ...

Ways to retrieve an array following a function call

After a lot of testing and troubleshooting, I finally got my array to function properly in the console. However, when I click the button, the array is displayed on the console but not in my HTML. TS: jogar(){ for(var u=0;u<6;u++){ this.y ...

Dilemma of interdependencies between Socket.io and requirejs

I am facing a challenge with my legacy express project that has two servers. The project includes two separate client files: requirejs.config({ baseUrl: '/js' , paths: { "jquery": "lib/jquery/jquery-2.1.1.min", "socket.io" : "lib/socket/ ...

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

How can I implement disabling buttons for specific IDs in React?

I'm currently developing an interactive quiz application with React that features multiple choice questions. I've implemented state management to track and increment the user's score when they select the correct answer option, but there&apos ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Getting Checkbox Values with Laravel and jQuery

I am facing an issue where I am only able to retrieve one value from checkboxes in jQuery, even though multiple checkboxes have different values. Here is the code snippet: <form method="post"> @foreach($services as $service) ...

Ways to prevent endless loops from occurring?

Here is the code for my component: const Inscriptions = () => { // getting state const { inscriptions, loading } = useSelector( state => state.user ); // flag const instances = Object.keys(inscriptions).length; // dispatch ...