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

Are there any additional performance costs associated with transmitting JSON objects instead of stringified JSON data through node.js APIs?

When developing node.js APIs, we have the option to send plain JSON objects as parameters (body params). However, I wonder if there is some extra overhead for formatting. What if I stringify the JSON before sending it to the API and then parse it back to i ...

What could be causing my jQuery switch not to function on the second page of a table in my Laravel project?

Having an issue with a button that is supposed to change the status value of a db column. It seems to only work for the first 10 rows in the table and stops functioning on the 2nd page. I'm new and could really use some help with this. Here's the ...

Express always correlates the HTTP path with the most recently configured route

Recently, I encountered a strange issue with my Express routes configuration. It seems that no matter which path I request from the server, only the callback for the "/admin" route is being invoked. To shed some light on how routes are set up in my main N ...

A guide on renewing authentication tokens in the Nestjs framework

import { ExtractJwt, Strategy } from 'passport-jwt'; import { AuthService } from './auth.service'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable, UnauthorizedException } from '@nestjs/common&apo ...

Add a color gradient to text as it animates without displaying any code tags (HTML, CSS, JS)

I have a unique text animation that loads when the page loads. The characters will be gradually written to the screen with some words having a gradient effect. While I've managed to successfully apply the gradient, there seems to be a pause when it re ...

Using JQuery and CSS to handle multiple hyperlink links with a single action

UPDATE: Issue resolved, thanks for the help. It is working fine now: http://jsfiddle.net/c3AeN/1/ by Sudharsan I have multiple links on my webpage, all in a similar format like this: note: When I say 'similar format', I mean that all links share ...

Warning issued by npm during compilation: The template string expression is unexpected as there should be no curly braces in the

Getting an npm warning during compiling (Unexpected template string expression no-template-curly-in-string) import React from 'react'; const Card = ({name, email, id }) => { return ( <div className='tc bg-light-green dib b ...

Using Typescript to Import One Namespace into Another Namespace

Is it possible to export a namespace from one typescript .d.ts file and then import that namespace into another .d.ts file where it is utilized inside of a namespace? For instance: namespace_export.d.ts export namespace Foo { interface foo { ...

What steps do I need to take in order to implement a functional pagination menu in Vue?

I downloaded and installed laravel-vue-pagination with the following command: npm install laravel-vue-pagination After that, I globally registered it in my app.js file: Vue.component('pagination', require('laravel-vue-pagination')); F ...

Please provide a list of combinations of dictionaries containing lists and lists containing dictionaries from a JSON file through the terminal

How can I retrieve a JSON data structure from the terminal that consists of nested lists and dictionaries in any combination, similar to the following example: [{"type":"one", "wrapped":[Slow, Empty, {"type":"tw ...

Error: Jest encounters an unexpected token 'export' when using Material UI

While working on my React project and trying to import { Button } from @material-ui/core using Jest, I encountered a strange issue. The error message suggested adding @material-ui to the transformIgnorePatterns, but that didn't resolve the problem. T ...

Create a duplicate of the table and remove specific rows

Hi there, I have a query about duplicating a table. I am looking to extract specific results and display only those results. To illustrate, here is an example in HTML code: <table class="table table-striped" id="ProfileList2"> <tbody> ...

Exploring the potential of utilizing functions in express.js to take advantage of the "locals"

Having experience with Rails/Sinatra, I am accustomed to using helper functions in my view files. However, incorporating this functionality into express.js has proven to be quite challenging. You can include locals automatically like this... app.set("nam ...

Adjusting the image placement within a modal window (using bootstrap 3)

Behold, an example modal: <!-- Large Modal --> <div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"> <div class="modal-dialog modal-lg"> <div class="modal-content"> ...

The Node gracefully disconnects and apologizes: "I'm sorry, but I can't set headers after they have already

events.js:160 throw er; // Unhandled 'error' event ^ Error: Can't set headers after they are sent. register.js:20:18 register.js user.save(function(err) { if(err){ return mainFunctions.sendError(res, req, err, 500, ...

Tips for showing only the date (excluding time) from a get operation in javascript (specifically using node js and mysql)

I recently built a CRUD application using Node.js and MySQL. However, I am facing an issue where I am unable to display the date without the time and in the correct format. { "id": 1, "name": "Rick Sanchez", "dob": & ...

Tips on implementing a jQuery .load() function using an anchor tag within dynamic content

I am working on a search page where user input is taken from a form and then sent to a PHP file that makes a cURL call to an external server. The PHP file receives an array from the server, which it uses to display HTML in a "results" div on the original s ...

Lookup and substitute using a lexicon

I have a JSON file containing a list of data elements, each with a field called URL. [ { ..., ..., "url": "us.test.com" }, ... ] In another file, I have a set of mappings that need to be used to replace the URLs in the JS ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Converting dynamic text enclosed in asterisks (*) into a hyperlink on a webpage with the use of JavaScript

I'm facing a unique situation where I need to transform specific text on an HTML page into anchor tags using JavaScript/jQuery. The text format is as follows: *www.google.co.uk/Google* *www.stackoverflow.com/StackOverflow* The desired outcome should ...