What is the best way to merge values in an array based on their keys?

Here is a sample of the data I have:

data = [
  [
    {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]},
    {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]}
  ],
  [
    {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]},
    {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]}
  ],
  [
    {"name":"cpumhz","data":[[1433856538,0],[1433856598,0]]},
    {"name":"mem","data":[[1433856538,13660],[1433856598,13660]]}
  ]
];

My question is how to utilize map to merge the arrays so that the data values are combined:

For example:

data = [
  [
    {"name":"cpumhz","data":[[1433856538,0],[1433856598,0],[1433856538,0],[1433856598,0], [1433856538,0],[1433856598,0]]},
    {"name":"mem","data":[[1433856538,13660],[1433856598,13660], [1433856538,13660],[1433856598,13660], [1433856538,13660],[1433856598,13660]]}
  ]
];

I have been attempting to achieve this manually as follows:

res = []

cpudata = _.flatten([data[0][0].data, data[1][0].data, data[2][0].data])
res.push({name: 'cpumhz', data: cpudata})

memdata = _.flatten([data[0][1].data, data[1][1].data, data[2][1].data])
res.push({name: 'mem', data: memdata})

Link to the corresponding exercise: http://jsbin.com/bekodirili/7/edit

Answer №1

Consider utilizing the reduce method. Other libraries like Underscore or lodash offer similar functionalities.

The concept is to streamline the data into a single array containing 2 values. The following snippet demonstrates how to achieve this:

var reducedData = data.reduce(function(prev, cur) {
    prev.forEach(function(value, index) {
        value.data = value.data.concat(cur[index].data);
    });

    return prev;
});

By iterating through each value in data and reducing it, you combine the previous sub-data with the current sub-data, resulting in a new value.

Answer №2

Using lodash library, you have the ability to accomplish the following:

_(data)
    .flatten()
    .groupBy('name')
    .reduce(function(result, item, key) {
        return result.concat([{
            name: key,
            data: _.flatten(_.pluck(item, 'data'))
        }]);
    }, []);

By utilizing the flatten() function, you can transform the data into an array and then group it based on the value under the key name using the groupBy() method. This process results in an object with properties named cpuhz and mem.

Finally, with the help of the reduce() function, it becomes straightforward to convert the object into the desired array format.

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

Every time I try to run npm start on my React app, I keep receiving the error message "? Something is already running on port 3000"

Whenever I try to start my React server, I keep receiving the message "? Something is already running on port 3000" in my terminal. Strangely, there is nothing actually running on port 3000. Here are the steps I have taken to try and solve this issue: Re ...

What is the best way to manage files in Vue.js?

I am faced with a challenge in storing image files and video files as Blob data. One thing I like is that the uploaded video and image files display instantly, which is pretty cool. I'm not entirely sure if the code below is correct - how can I navi ...

Retrieve information from the script tag

Is there a method to extract data from a <script> tag, specifically targeting the 30-minute table on AEMO's website (AEMO Website)? In order to access the data table, I attempted to scrape it but encountered an issue where the button and table ...

What sets Vue.js apart, class and staticClass - is there a distinction?

Can someone explain the distinction between class and staticClass in Vue.js render functions? While using Template Compilation, I noticed that the output varies based on what is provided to the HTML class attribute. For instance, when passing a single str ...

Adding EventListeners for Click Handling: A Step-by-Step Guide

Here is the part of my code in HTML: <!DOCTYPE html> <html> <head> <h> <title> This page</title> </h> </head> <body> <button id = "go-button" >GO ...

A collection of functions embedded within a JSON data structure

I am working with a website that provides data in a JSON-like format similar to the following: { "name":"tom jones", "no": 123, "storedproc": function(){ callbuyer(0123); } } Currently, I am using $. ...

Is my input file in Javascript valid and does it exist? Here's how to check

In my Javascript code, I am retrieving strings from a text file. When the user inputs an incorrect or invalid file name, I want to display a message. For example: console.log("Your input is invalid"); Here is the code snippet that reads the text file and ...

Combining duplicate key-value pairs in a JSON object into an array using JavaScript

Is it possible to merge value objects with the same key but different values? For example, in this case, "field_template_id": 2 appears twice with different values. This is the original JSON data: { "id": "c2dec94f", "data": [ { "field_temp ...

Create a dynamic progress bar that integrates seamlessly with the ajaxupload functionality for a smoother video uploading

Is there a way to display an accurate time estimate alongside a visually appealing progress bar during video uploads? Currently, I am utilizing the ajaxupload javascript library in conjunction with PHP CodeIgniter for server-side functionality. ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

Discovering a way to retrieve objects from an array of objects with matching IDs

Here is a code snippet I put together to illustrate my objective. arr = [ { id:1 , name:'a', title: 'qmummbw' }, { id:2 , name:'b', title: 'sdmus' }, { id:2 , name:'', title: 'dvfv' }, ...

How can I dynamically assign @ViewChild('anchor_name') to a newly updated anchor element in Angular 2+?

Upon receiving an item through a GET request, I set the item_id upon subscription. In the HTML file, I create a div with an anchor id="{{this.item_id}}". However, I encountered the following error: FeedComponent.html:1 ERROR TypeError: Cannot read propert ...

NodeJS paired with AngularJS

Recently, I've been diving into AngularJS and NodeJs, but have encountered a few hurdles. Firstly, I'm trying to load index.html or other files, currently I'm doing it manually and in the simplest way possible, but I keep running into issue ...

Ways to enable an Angular 5 web application to launch in multiple tabs within a single browser

Is there a way to open an Angular 5 app in multiple tabs of Chrome? Are there any methods or caching processes that can assist with this task? ...

Simplify a JSON array in JavaScript by removing nested layers

Looking to flatten a JSON nested array object into a flat array The key and value pair should be dynamic based on user input array I attempted to write the code myself but I'm not very familiar with JavaScript functions like concat, push, or others. ...

Can you provide me with some insight on the process of iterating through an object utilizing the

I've developed an app that randomly plays a sound from a selected array when a button is pressed. Now, I want to add the functionality to display and play all sounds in the array upon request. I've explored various methods such as for loops and ...

Discover the location following a designated distance along a direct path connecting two points in the Google Maps API

Using the Google Maps API, I have plotted a straight line from point P1 to point P2. Both points have latitude and longitude coordinates available. I am interested in finding a point (P) along this straight line, located at a specific distance from P1. F ...

Angular's separate scope variables allow for isolated data manipulation within individual components

Struggling with one scope variable affecting multiple elements in a div in AngularJS. Looking for help as a beginner in handling this issue. For a clearer understanding, here's an example: JS: /* controller-home.js ********************************* ...

Efficient method for handling numerous AJAX requests

I have a web application that currently makes 14-15 AJAX calls to various APIs. The issue is that the combined time it takes for all the AJAX calls to complete is significantly longer than when I individually type each API's URL into the browser. Cur ...

Is the callback for a request always invoked?

When using the npm module request, I often encounter situations where some requests are not called back, leading to various issues. This has raised a question in my mind - is it expected for the request function to always callback? For instance, if my req ...