Aggregate objects inside array in js

Souames

I have an array like the following:

[ 
 {"sku": 123, "val": 10},
 {"sku": 124, "val":12},
 {"sku": 123, "val": 20}

]

Is there a quick way in javascript to sum val of objects with the same sku property, so the result would be:

[ 
 {"sku": 123, "val": 30},
 {"sku": 124, "val":12}
]
Mr. Polywhirl

You should group the entries by their SKU and then map the entries to an SKU and the reduced (sum of) values.

const data = [ 
 { "sku": 123, "val": 10 },
 { "sku": 124, "val": 12 },
 { "sku": 123, "val": 20 }
];

const groupBy = (arr, key) => arr.reduce((acc, entry) => ({
  ...acc, [entry[key]]: [ ...(acc[entry[key]] || []), entry ]
}), {}); 

const sum = Object.entries(groupBy(data, 'sku'))
  .map(([key, values]) =>
    ({
      'sku': key,
      'val': values.reduce((acc, { val }) => acc + val, 0)
    }))

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

Here is a more dynamic version that allows for multiple reducers with various aggregation techniques.

const groupBy = (arr, key) => arr.reduce((acc, entry) => ({
  ...acc, [entry[key]]: [ ...(acc[entry[key]] || []), entry ]
}), {}); 

const aggregate = (arr, key, reducers) =>
  Object.entries(groupBy(arr, key))
    .map(([k1, values]) => Object.entries(reducers)
      .reduce((obj, [k2, { fn, initial }]) => ({
        ...obj,
        [k2]: values.reduce((acc, item, index, all) =>
          fn(acc, item[k2], index, all), initial || 0)
      }), { [key]: k1 }))

const data = [ 
 { "sku": 123, "val": 10, "val2": 2 },
 { "sku": 124, "val": 12, "val2": 5  },
 { "sku": 123, "val": 20, "val2": 8  }
];

const aggregated = aggregate(data, 'sku', {
  'val'  : { fn: (acc, val) => acc + val, initial: 0 },
  'val2' : { fn: (acc, val) => acc * val, initial: 1 }
});

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

MongoDB aggregate $group $sum that matches date inside array of objects

Filter array of objects inside another array in JS

JS Sort array of objects with array inside

Aggregate an array of objects in JavaScript

Aggregate $lookup Array of Objects

MongoDB aggregate objects with an array of objects?

How to append objects to a key inside JS array?

Merge corresponding objects inside array JS

How to join JS objects inside an array? Onliner

array of objects inside array of objects

Aggregate data from array of objects

Mongodb Aggregate query to sum all values based on fields inside objects in an Array

JS: Aggregate Array of object

How to get value from array, which is inside objects in react js?

Node.js - How to merge objects inside an array based on condition?

How to extract values of a property inside an array of objects- JS

jQuery/JS – Outputting objects inside an array – best practice

Sum values of objects which are inside an array with underscore.js and reduce

Spread Operator to get single property of objects inside an Array - JS/TS

React.js - Unable to access values inside array of objects

Search the String inside array of Objects using underscore.js

clearTimeout not working for timeout inside an array of objects in Node.js

How to count multiple objects inside nested array sequentially in react js

Using this inside array of objects

mapping objects inside an array

Combine the objects inside the array

Array iteration inside array of objects

Sort an array inside an array of objects

$lookup inside $lookup in array of objects inside array