Efficiently calculating multiple sums of objects with d3.js

My current object structure is:

{
  [

      {  id: "AL01",
         list: [
                  { speed : 5
                    value : 10} , 
                  { speed : 7
                    value : 15}
               ]
     }, 
     {  id: "AB01",
        list: [
                { speed : 20
                  value : 1} , 
                { speed : 8
                  value : 10}
              ]
     }

 ]

}

I aim to transform it into the following format:

{[ {  id: "AL01", speed: 12, value: 25}, {  id: "AB01", speed: 28, value: 11}]}

What is the most efficient way to achieve this? Is it possible to use the map or forEach functions only once? I am looking for a solution that processes each object only once.

Answer №1

Your current data structure needs adjustment. You must include a property for the outermost array in your data object. Here's how you can rectify it:

var data = {groups: [ {id: "AL01", list: [{ speed : 5, value : 10}, { speed : 7, value : 15}]}, {id: "AB01", list: [{ speed : 20, value : 1 }, { speed : 8, value : 10}]}]},
  result = {groups: data.groups.map(g => Object.assign({id: g.id},g.list.reduce((r,c) => ({speed : r.speed + c.speed, value : r.value + c.value})))};
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To achieve the desired outcome, it is essential to incorporate additional loops.

Firstly, work through the outer array, then proceed to iterate over the list and introduce another array for the keys. Subsequently, gather all relevant data and generate a new object with an alternative structure.

var array = [{ id: "AL01", list: [{ speed: 5, value: 10 }, { speed: 7, value: 15 }] }, { id: "AB01", list: [{ speed: 20, value: 1 }, { speed: 8, value: 10 }] }],
    result = array.map(function (a) {
        var temp = { id: a.id, speed: 0, value: 0 };
        a.list.forEach(function (b) {
            ['speed', 'value'].forEach(function (k) {
                temp[k] += b[k];
            });
        });
        return temp;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

"Converting array into a string in TypeScript/Javascript, but unable to perform operations

After generating a string with the correct structure that includes an array, I am able to navigate through the JSON on sites like However, when attempting to access the array, it turns out that the array itself is null. Here is the scenario: Firstly, th ...

Encounter the error message "Socket closure detected" upon running JSReport in the background on a RHEL system

I'm encountering an issue with JSReport at www.jsreport.net. When I run npm start --production in the background, everything seems to be working fine. But as soon as I close this session, an error pops up: Error occurred - This socket is closed. Sta ...

Is there a way to extract values from EditText and store them as a sum in an array?

Suppose I have two Edit-text fields, for example. My goal is to retrieve the values entered by the user in them and sum the values in an array. Let's say the code looks like this. EditText oneValue = (EditText)addView.findViewById(R.id.one); EditTex ...

Adjust the quantity of divs shown depending on the value entered in a text input field

It seems like I am on the right track, but there is something simple that I am missing. I'm currently utilizing the jQuery knob plugin to update the input field. $('document').ready(function() { $(".knob").knob({ c ...

Disabling the scroll-bar feature exclusively

Is there a way to disable the scroll-bar functionality in Chrome without hiding it using overflow:hidden? I want the scroll-bar to remain visible. I'm looking for something similar to this: http://prntscr.com/ai5y9k Any assistance would be greatly a ...

What is the best way to incorporate a vanilla javascript function into a vue.js application?

Consider a vanilla JavaScript function like this: if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); i ...

The use of React input sliders with Hooks is a powerful

Currently, I am working on creating an input slider using React Hooks that shows the number corresponding to the slider's position. However, I have encountered a problem where the slider is not responsive when moving backwards and is very slow to resp ...

Challenge encountered with asynchronous angular queries

Dealing with asynchronous calls in Angular can be tricky. One common issue is getting an array as undefined due to the asynchronous nature of the calls. How can this be solved? private fetchData(id){ var array = []; this.httpClient.get('someUrl ...

Creating a 2D matrix with for loops in Python

I am seeking a way to generate a matrix using loops, with the following structure: matrix = [[x - 3 , y - 3], [ x - 2 , y - 3], [x - 1, y - 3], [ x , y - 3], [x - 3, y - 2], [x - 2, y - 2], [x - 1, y - 2], [x, y - 2], [x - 3, ...

What is the best way to divide a string following the nth instance of a particular character?

In my JavaScript code, I am facing an issue with splitting a string. Here is the string that I need to split: var str = 'Lenovo Essential G500s (59-388254) Laptop (3rd Gen Ci5/ 8GB/ 1TB/ DOS/ 2GB Graph) (Free carry bag) (Black)'; My goal is to ...

Show information in a horizontal layout, but switch to a stacked arrangement if the screen is too narrow

Is there an optimal way to arrange content side by side when the width allows, like this: [content] [content] [content] [content] If the screen becomes too small, should the content automatically stack like this: [content] [content] [content] I am ...

Grouping and populating in Mongoose: A comprehensive guide

My preferred ODM setup consists of MongoDB and Mongoose. Currently, I am facing a challenge while attempting to execute a query that involves both populate and group by in a single statement. Let me share the basic structure of my document models: var us ...

The transition from ExtJS 4 to ExtJS 5: A comprehensive guide

We're in the process of transitioning a web application from ExtJS 4 to ExtJS 5. Upon testing the index.html, we encountered an error message (displayed in the Firefox-FireBug-console): NetworkError: 404 Not Found - http://localhost:8080/ext/build/e ...

Information sent by the Firefox TCP socket using the socket.send() method cannot be retrieved until the socket is closed

I am experiencing an issue while trying to send data from Firefox to a Java desktop application. My Java class functions as a server, and the Firefox script acts as a client. When I test it using another Java class called client.java, the data is successfu ...

Failure to Trigger AJAX Success Event

I am facing an issue while trying to retrieve a JSON string using an ajax call with JQuery. Despite getting a code 200 and success from the complete method, the success method itself is not triggering. function initialize() { $.ajax( { type ...

Acquire the text within an anchor tag using JavaScript

Is it possible to invoke a search for all links on my Wordpress blog? I'm not sure if my idea is correct. Currently, I am using an Ajax call for another search on this site. How can I extract the text from a hyperlink HTML tag? For example: <a href ...

Discovering all jQuery functions employed in a JavaScript file can be accomplished through the utilization of regular expressions

I have a somewhat unconventional idea that I want to share. The project I'm currently working on has an old front-end codebase that is causing the website to run slowly, with jQuery being a major factor. My plan is to develop a tool that can analyze a ...

List-style-type outside of a table's boundaries

I recently experimented with using <ol> as list elements within a table in order to dynamically insert new table rows. <table> <thead> <tr> <th>head</th> <th>head</th> <th>h ...

extract information from a JavaScript string

I have a sequence that looks like this: coordinates = '15,-2,-3,15' This sequence corresponds to points, specifically A(15, -2), B(-3, 15). Q How can you retrieve the data from a string in this format? It would be ideal to obtain the results ...

Is there a way to save a user-inputted HTML table to local storage and later showcase it on a separate results HTML page?

Here is the overview of my program: Users fill in an HTML table (this step is working fine) on the table.HTML page The HTML table is saved in localStorage (using .SET on table.innerHTML) The HTML table is viewed (using .GET) on a different results.HTML pa ...