Grouping an array of arrays of objects

I am trying to group an array of objects based on the value of the first item below:

const data = [{"value":"value1","metric":1},{"value":"value1","metric":2},{"value":"value3","metric":0},{"value":"value2","metric":4},{"value":"value3","metric":1},{"value":"value3","metric":1}];

const result = [...data.reduce((acc, obj) => {
  const key = obj.value;
  
  const item = acc.get(key) || Object.assign({}, obj, {
    metric: 0,
  });
  
  item.metric += obj.metric;

  return acc.set(key, item);
}, new Map).values()];

console.log(result);

However, I am facing difficulties when dealing with an array of arrays of objects like this:

[[{"value":"value1","formattedValue":"value1"},{"value":2831.8,"formattedValue":"283,180.00 %"}],[{"value":"value1","formattedValue":"value1"},{"value":349.1111111111111,"formattedValue":"34,911.11 %"}],[{"value":"value2","formattedValue":"value2"},{"value":3.3703703703703702,"formattedValue":"337.04 %"}]]

The difference here is that instead of a single object like this:

{"value":"value1","metric":1}

We now have an array of objects like this:

[{"value":"value1","formattedValue":"value1"},{"value":"1.0","formattedValue":100.00 %}]

An approach could be transforming the second query to match the format of the first one, but I would like to find a solution while using the function previously mentioned.

The desired output should look like this:

[[{"value":"value1","formattedValue":"value1"},{"value":3180.91111111,"formattedValue":"318091.11 %"}],[{"value":"value2","formattedValue":"value2"},{"value":3.3703703703703702,"formattedValue":"337.04 %"}]]

Answer №1

To update the result set, you can destructure the key/value pair.

var data = [[{ value: "value1", formattedValue: "value1" }, { value: 2831.8, formattedValue: "283,180.00 %" }], [{ value: "value1", formattedValue: "value1" }, { value: 349.1111111111111, formattedValue: "34,911.11 %" }], [{ value: "value2", formattedValue: "value2" }, { value: 3.3703703703703702, formattedValue: "337.04 %" }]],
    result = Array.from(
        data
            .reduce((m, a) => {
                var [{ value: key }, { value }] = a,
                    target = m.get(key);

                if (!target) return m.set(key, JSON.parse(JSON.stringify(a)));
                target[1].value += value;
                target[1].formattedValue = `${(target[1].value * 100).toFixed(2) } %`;
                return m;
                
            }, new Map)
            .values()                
    );        

   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

Encountering issues with link functionality on homepage due to React-Router v6 and Material-UI Tab integration

I'm currently working on a homepage that requires different page links. Below you can find the necessary code snippet for setting up the tabs and routes for each page: <li> The tabs are located here - <Link to="/demo">D ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

Display images on a single dataset using Chart.js

How can I create a doughnut chart with 2 datasets where only one of them displays images? I managed to render both datasets and add images using chartjs-plugin-labels, but it applies the images to both datasets. Is there a way to specify which dataset shou ...

Exploring D3 to extract nested information and build an interactive navigation tree

Recently, I've been working with d3's zoom circle feature from here: The data I'm dealing with is structured as a json array with various levels of arrays and objects. object = { class: "show", name: "Game of Thrones", childre ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

The nested promise.all function is executing synchronously instead of asynchronously as anticipated

Within the nested Promise.all section of my NodeJs script, I believe there is an error. The script is designed to process multiple .csv files within a directory, creating a database record for each row. If a row fails processing, it is added to a list of f ...

The webpage's Document Object Model fails to refresh following a JavaScript modification

I have encountered an issue with a sample webpage where I am attempting to set the wmode of all YouTube elements on the page to "transparent." When inspecting the page using Chrome, I can see that my JavaScript code is functioning properly. However, the b ...

Proper positioning of try/catch block in scenarios involving delayed async/await operations

For the past six months, I have been utilizing async/await and have truly enjoyed the convenience it provides. Typically, I adhere to the traditional usage like so: try { await doSomethingAsync() } catch (e) {} Lately, I've delved into experimenti ...

What is the best way to create a page that moves on release using HTML/CSS?

I'm working on a website where I want to make an interactive feature. When users click on an image on the left side of the page, I want the page to move backward. Similarly, when they click on an image on the right side, I want the page to move forwar ...

Addressing the issue of prolonged Electron initialization

Scenario After spending considerable time experimenting with Electron, I have noticed a consistent delay of over 2.5 seconds when rendering a simple html file on the screen. The timeline of events unfolds like this: 60 ms: app ready event is triggered; a ...

maintaining accountability in package.json

Adding commas to the last element of an object or array in package.json can impact how blame is preserved. For example, if we start with this code in commit A: { "version": "0.0.1" } Then in commit B, another field is added: { "version": "0.0.1", ...

Unable to communicate with MediaWiki API using jQuery

My attempt to retrieve content from Wikipedia in JSON format has been unsuccessful: $.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json", function(data) { doSomethingWith ...

Swap out the image backdrop by utilizing the forward and backward buttons

I am currently working on developing a Character Selection feature for Airconsole. I had the idea of implementing this using a Jquery method similar to a Gallery. In order to achieve this, I require a previous button, a next button, and the character disp ...

Fetching json data from the request in Node.js

I'm currently working on a project that involves using the request module to send an HTTP GET request to a specific URL in order to receive a JSON response. However, I've run into an issue where my function is not properly returning the body of ...

How can you create an event that is focused on options using Material-UI's Autocomplete feature?

This is regarding Material-UI's Autocomplete feature. I am looking for a way to track which autocomplete choice the user is currently focused on, whether it be through hovering over with the mouse or using keyboard arrows - before any actual selection ...

EmberJS - how to register a precompiled handlebars template

In my EmberJS application, I have precompiled all of my handlebars templates so that they are loaded as pure Javascript files. However, I am encountering an issue where these precompiled templates are not being added to the Ember container as expected. In ...

Retrieve the Vue.js JavaScript file from the designated static directory

This is my inaugural attempt at creating a web application, so I am venturing into Vue.js Javascript programming as a newcomer. I have chosen to work with the Beagle Bootstrap template. Within my Static folder, I have a file named app-charts-morris.js whi ...

How to access a webpage on your Android device without the address bar visible

My question relates to sending Push Notifications through OneSignal. Upon clicking a push notification, it automatically redirects the user to my website. Is there a way to hide the address bar on the browser when this happens? I attempted using the follo ...

Checking the response from an AJAX call with an if/else statement

Is there a way to create a counter for unread messages using PHP and jQuery? Below is the PHP code in BubbleStat.php: $totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessio ...

Best practices for effectively managing a sizable dataset in Vue.js

My task at hand is to create a visualization dashboard that can operate solely in the browser, utilizing Vue.js, D3, and JavaScript. The dataset I am working with is stored in a .json file that is 48 MB in size. However, upon parsing the file using d3.json ...