Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce array of objects on key and sum value into array

I have the following object:

data = [
  { name: 'foo', type: 'fizz', val: 9 },
  { name: 'foo', type: 'buzz', val: 3 },
  { name: 'bar', type: 'fizz', val: 4 },
  { name: 'bar', type: 'buzz', val: 7 },
];

And used lodash map:

result = _.map(data, function item, idx){
  return {
    key: item[key],
    values: item.value,
  }
}

Which results in:

[
  { key: foo, val: 9 },
  { key: foo, val: 3 },
  { key: bar, val: 4 },
  { key: bar, val: 7 },
]

but now I'm trying to return:

[
  { key: 'foo', val: 12 },
  { key: 'bar', val: 11 },
]

I tried using reduce which seems to only output to a single object, which I could then convert back into an array, but I feel like there must be an elegant way to use lodash to go from my source data straight to my desired result without all of the intermediate steps.

I thought this was addressing my exact problem, but it seems like quite a bit of work just to have to convert the object into the desired array of objects outlined above.

Cheers.

like image 808
Jesse Avatar asked Jun 02 '16 19:06

Jesse


People also ask

How do you reduce to sum an array of objects?

The array reduce in JavaScript is a predefined method used to reduce an array to a single value by passing a callback function on each element of the array. It accepts a function executed on all the items of the specified array in the left-to-right sequence. The returned single value is stored in the accumulator.

Can you use reduce on objects?

reduce can use initial and return values of any type, which makes it very flexible. Let's explore how we can use it to perform some common tasks with plain objects.

How do you reduce an array of arrays?

Using the reduce method. The reduce() method executes a reducer function (a function that you provide as an argument) on each element of the array, resulting in a single output value. Here, the reducer function provided is concat() and the result is stored in an empty array.

What is the reduce () array method?

The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.


1 Answers

A twist to the accepted answer that uses groupBy instead of reduce to do the initial grouping:

var result = _.chain(data)
    .groupBy('name')
    .map((group, key) => ({ key, val : _.sumBy(group, 'val') }))
    .value();
like image 104
Gruff Bunny Avatar answered Sep 28 '22 00:09

Gruff Bunny