javascript categorize data by key and display in a tabular format

I have a Client ID and gender information available. Shown below is a JSON response along with a JavaScript function to display the data in a table format. The JSON response structure is as follows:

studies = [{
    "id": {
        "Value": [
            "1"
        ]
    },
    "gen": {
        "sex": "M"
    }
} ,
{
    "id": {
        "Value": [
            "1"
        ]
    },
    "gen": {
        "sex": "M"
    }
} ,
{
      "id": {
        "Value": [
            "1"
        ]
      },  
      "gen": {
        "sex": "M"
    }
},
{
    "id": {
        "Value": [
            "2"
        ]
    },
    "gen": {
        "sex": "F"
    }
} 
 ]

The JavaScript function used to print the table is:

function () {
                var studies  = JSON.parse(this.responseText);            
                var table = createTable([ "ID", "Gender"]);

                // ADDING JSON DATA TO THE TABLE AS ROWS.
                for (var i = 0; i < studies.length; ++i) {
                    tr = table.insertRow(-1);
                    var study = studies[i];
                    tr.insertCell(-1).innerHTML  = study["id"].Value[0];
                    tr.insertCell(-1).innerHTML  = study[""gen]["sex"];
                }

                var divContainer = document.getElementById("employee list");
                divContainer.innerHTML = "";
                divContainer.appendChild(table);
            }

The current table output can be viewed here.

Question: I am attempting to group the data by ID and display it on the table //result -> 2 rows with ID 1 & 2

Seeking guidance on the most appropriate method to achieve this. The reduce function would generate an object, however, I aim to avoid creating a new object and directly displaying the results in the table.

Feeling confused! Any assistance would be greatly appreciated!

Answer №1

One way to keep track of displayed elements is by storing their IDs in an array.

function () {
    var data = JSON.parse(this.responseText);            
    var table = createTable(["ID", "Gender"]);

    var ids = [];
    // LOOP THROUGH THE DATA AND ADD UNIQUE ROWS TO THE TABLE.
    for (var i = 0; i < data.length; ++i) {
        var item = data[i];
        if (!ids.includes(item["id"].Value[0])) {
            ids.push(item["id"].Value[0]);
            tr = table.insertRow(-1);
            tr.insertCell(-1).innerHTML = item["id"].Value[0];
            tr.insertCell(-1).innerHTML = item["gen"]["sex"];
        }
    }

    var container = document.getElementById("employee list");
    container.innerHTML = "";
    container.appendChild(table);
}

Answer №2

To accomplish this task, it is recommended to maintain a collection of used IDs in an array.

function () {
                var data  = JSON.parse(this.responseText);            
                var table = createTable([ "ID", "Category"]);
                const idArray = []
                
                // Populate the table with unique rows based on ID.
                for (var j = 0; j < data.length; ++j) {
                    var item = data[j];
                    if(!idArray.includes(item["id")]) {
                       tr = table.insertRow(-1);
                       tr.insertCell(-1).innerHTML  = item["id").Value[0];
                       tr.insertCell(-1).innerHTML  = item[""cat]["type"];
                       idArray.push(item["id"].Value[0]);
                    }
                }

                var container = document.getElementById("list of items");
                container.innerHTML = "";
                container.appendChild(table);
            }

Answer №3

Here's an example of the code you currently have, where you iterate over all rows:

var studies  = studies = [{"id": {"Value": ["1"]},"gen": {"sex": "M"}} ,{"id": {"Value": ["1"]},"gen": {"sex": "M"}} ,{"id": {"Value": ["1"]},  "gen": {"sex": "M"}},{"id": {"Value": ["2"]},"gen": {"sex": "F"}}];       


for (const [key, values] of Object.entries(studies)) {
  console.log(`${values.id.Value}, ${values.gen.sex}`);
}

If you wish to display each row based on id and gender, you'll need to store those values and then check if they have already been printed. Here's a modified version:

var studies  = studies = [{"id": {"Value": ["1"]},"gen": {"sex": "M"}} ,{"id": {"Value": ["1"]},"gen": {"sex": "M"}} ,{"id": {"Value": ["1"]},  "gen": {"sex": "M"}},{"id": {"Value": ["2"]},"gen": {"sex": "F"}}];       


var alreadyPrinted = {'M' : [], 'F': []};

for (const [key, values] of Object.entries(studies)) {
  if(alreadyPrinted[values.gen.sex].includes(values.id.Value[0])) {
    continue;
  }
  
  alreadyPrinted[values.gen.sex].push(values.id.Value[0])
  console.log(`${values.id.Value[0]}, ${values.gen.sex}`);
}

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

Trouble with integrating HTML5 canvas from an external JavaScript file

Having trouble with storing canvas js in an external file. If the javascript responsible for drawing on the canvas is included in the html header, then the rectangle is displayed correctly. Here is the working html (javascript in html header): <!DOCT ...

Guide on restricting the character count and displaying the leftover characters using PHP with Ajax

I've been working on implementing a feature to display the remaining characters in a PHP AJAX call. I was successful using JavaScript, but I'm having trouble doing it with AJAX in PHP. Can someone provide assistance? <script type="text/javasc ...

When tab switching occurs, the alert box fails to be processed by the browser

When using the alert(message) function, it will display an alert box with a message and an OK button. It will also pause the execution of any code that follows until the OK button is clicked. However, I have noticed a peculiar situation where switching tab ...

Using setTimeout to click and hold on an element in Javascript

I am in need of adding a feature to my web app where a specific action is triggered when the user clicks and holds on an element, similar to the long press on Android. Here is the HTML code for my div: <div id="myDiv" onmousedown="press()" onmouse ...

Unable to retrieve the JSON response sent by the REST API within an HTML page

My ajax function is unable to properly receive the JSON content generated by a REST API. The REST API successfully creates the JSON data, but when passed to my ajax function, it does not work as expected. function loadJsonData(){ var dropDownValue = ...

Utilizing Vuex to Access a Component's Property in Vue

Utilizing Vuex in my app is integral for executing asynchronous tasks, such as logging a user into the application. Upon successful login and execution of axios.then(), I aim to notify the component from which I invoked this.$store.dispatch('login&apo ...

Typescript Routing Issue - This call does not match any overloads

Need assistance with redirecting to a sign-up page upon button click. Currently encountering a 'no overload matches this call' error in TypeScript. Have tried researching the issue online, but it's quite broad, and being new to Typescript ma ...

Sending requests across domains from HTTPS to HTTP with callback functionality, and reversing the process

Prior to our conversation, I had created it using Flash. I uploaded a special file (crossdomain.xml) on the server side (https), while the Flash component was placed on the http server. Although they belong to different domains on the https and http serv ...

What is the process of transforming a list of arrays, which is in JSON format, into Dart?

Having trouble with the JSON_ANNOTATION feature when dealing with a json that contains nested arrays. Uncertain about how to convert the paths in the array into a single Paths object. Maybe something like this, but it doesn't seem to handle multiple ...

Showing JSON data in AngularJS

I need help with AngularJS to display JSON output. Is using gridOptions the best approach for this? I'm trying to print labels starting from the root in reverse order - label/parent's label/parent's parent's label/... { artifac ...

How can the end event of a custom CSS animation be bound using jQuery or JavaScript?

We are currently managing multiple animations on the same object and need to execute different actions once each animation is complete. At present, we listen for the webkitAnimationEnd event and use a complex if/then statement to handle each animation sep ...

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Navigating horizontally with buttons in VueJS

I am searching for a way to implement horizontal scrolling using buttons in VueJS. The idea is to have a container with multiple divs arranged horizontally, and I wish to navigate through them using the buttons. If you want to see a similar solution using ...

What would be an effective method for sending a multitude of parameters to a controller?

I am currently working on an application that utilizes Java with the Spring framework and Javascript with AngularJs framework. The application features a table displaying a list of objects along with two text fields for filtering these objects. The filteri ...

Tips for retrieving data from a nested Axios request?

Currently, I am working on a series of steps: Phase 1: Initiate an Axios call to verify if the record exists in the database. Phase 2: In case the record does not exist, trigger a POST API call to establish the data and retrieve the POST response. Pha ...

Learn how to easily copy the success result from an Ajax call to your clipboard

Is there a way to use an ajax method to retrieve data from a controller and display it in a JQuery Dialog Box? I want to add a button within the dialog box that allows the user to easily copy the data with a single click, instead of having to manually high ...

JavaScript event handler for dynamic button click

I am creating a unique button dynamically for each row in a table to handle deletions. I am assigning the id of the button with the key of the row, allowing me to retrieve it later when clicked. Since all buttons share the same function, passing the specif ...

How can I make a variable available on the client side by exporting it from my Node JS server built with express framework?

How can I send a variable from my Node JS server, which is built using Express, to be accessed on the client side? I need this variable to hold a value stored locally on the server and then access it in my client side JavaScript code. I discovered that ...

Changing a JSON Object into an Array Structure in Swift 4

I received the following JSON data: { "message": null, "data": { "Commodity Department": { "total": 2, "completed": 1, "completedWithDue": 0, "completedWithOutDue": 1, "inProgress": 1, "inProgressWithDue": 0, ...

Learn how to display separate paragraphs upon clicking a specific item

New to coding and eager to learn, I have recently started exploring HTML, CSS, and basic JavaScript. In my journey to enhance my skills, I am working on building a website for practice. One particular page of the site showcases various articles, each acc ...