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

Swapping values between HTML tables and arrays with the power of JavaScript

I have a unique table structure that I need help with: My current table has 2 rows and multiple columns, but I want to change it to have 2 columns and multiple rows like this: To create the table, I am using two arrays named milestone and milestoneDate. ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

Load grid data only when the tab is clicked in ExtJS

Our app features a dynamic grid loaded with multiple tabs, each containing one or more grids. The issue currently is that when the application loads, it automatically calls all the URLs instead of waiting for the user to click on a tab. We want to optimi ...

Looking for assistance in reducing the vertical spacing between divs within a grid layout

Currently, I am in the process of developing a fluid grid section to showcase events. To ensure responsiveness on varying screen resolutions, I have incorporated media queries that adjust the size of the div elements accordingly. When all the divs are unif ...

When attempting to execute a script that includes document.write, it will not function as expected

Our web program is utilizing ajax and jquery, specifically Netsuite. I've been attempting to adjust elements on a page using document.ready and window.load methods in order to load an external script onto the page. Regardless of whether I load this ex ...

What is the reasoning behind declaring certain variables on the same line as others, while most are declared individually on separate lines?

I've taken on the challenge of learning JS by myself and decided to build a Blackjack game. While following a helpful walkthrough online, I encountered some confusion. On the website, they start by declaring Global variables: var deck; var burnCard; ...

Storing and Retrieving Cookies for User Authentication in a Flutter Application

I am currently working on developing a platform where, upon logging in, a token is created and stored in the cookie. While I have successfully implemented a route that stores the cookie using Node.js (verified in Postman), I encounter issues when attemptin ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...

Updating the scope in Angular when changing the image source using ng-src is not working

A snippet inside my controller looks like this: $scope.onFileSelect = function($files) { for(var i = 0; i < $files.length; i++) { var file = $files[i]; $scope.upload = $upload.upload({ url: '/smart2/api/files/profi ...

The condition in a Typescript function that checks for strings will never evaluate to true

I encountered a strange issue with a TypeScript condition in a function. Here is my current code, where the parameters are passed from outside: getLevel(validation: string, status: string): string { let card = ""; if (validation == &qu ...

Removing a value from a JavaScript object

Looking to delete a specific value from an object with multiple values? This is how my object is structured: { 'how can i change my password?': [ 'how can I change my password?', 'how may I change my password?', ...

Acquiring information from a different Vue.js component

I am faced with a puzzle involving 2 components, A and B. Component A: import B from '../components/B.vue'; export default { components: { B }, methods: { test: function() { console.log(B.data().settin ...

Tips for adjusting the font size of a Chip using Material-UI

I am using a widget called Chip const styles = { root:{ }, chip:{ margin: "2px", padding: "2px" } } const SmartTagChip = (props) =>{ const classes = useStyles(); return( <Chip style={{color:"white&q ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

Resizing an image with six corners using the canvas technique

Currently, I am facing two issues: The topcenter, bottomcenter, left and right anchors are not clickable. I'm struggling with the logic to adjust the image size proportionally as described below: The corner anchors should resize both height and wi ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...

Modifying multiple objects with Vue's V-Model

When utilizing the mounted function in Vue to assign two different objects in the data area and bind one of them to a form, an unusual issue arises: Both objects change when input values are entered in the form For example: <template> <v-card ...

The HttpParams are reluctant to be established

Working with Angular 8, I am attempting to assign an HttpParam using the provided code snippet and observing the outcome on the final line. let newParams = new HttpParams(); newParams.set('ordering', 'name'); console.log('getting: ...

Is it possible for me to create a lineString connecting two points in OpenLayers3?

I need to create a lineString connecting my two given points, such as [-110000, 4600000] and [0, 0]. ...

Determining the specific button pressed using jQuery

There are two buttons present: <input type="button" name="hideAll" value="Hide Descriptions"/> <input type="button" name="showAll" value="Show Descriptions"/> Can someone guide me on how to determine which button has been clicked using jQuery ...