Skip to content

JavaScript reduce array of objects by key | Example code

  • by

Use reduce() method with findIndex() method to reduce array of objects by key in JavaScript. This allows you to group the objects in the array by the value of the key and return a new object with the grouped data.

JavaScript reduces an array of objects by key

Simple example code Reduce array of objects on key and sum value into an array.

const 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
  },
]

const result = data.reduce((acc, curr) => {
  const index = acc.findIndex(item => item.name === curr.name)
  index > -1 ? acc[index].val += curr.val : acc.push({
    name: curr.name,
    val: curr.val
  })
  return acc
}, [])

console.log(result)

Output:

JavaScript reduce array of objects by key

How do calls reduce an array of objects to sum their properties?

Answer: A cleaner way to accomplish this is by providing an initial value as the second argument to reduce:

The first time the anonymous function is called, it gets called with (0, {x: 1}) and returns 0 + 1 = 1. The next time, it gets called with (1, {x: 2}) and returns 1 + 2 = 3. It’s then called with (3, {x: 4}), finally returning 7.

This also handles the case where the array is empty, returning 0.


var arr = [{x:1}, {x:2}, {x:4}];
var result = arr.reduce(function (acc, obj) { return acc + obj.x; }, 0);
console.log(result); 

Output: 7

var objs = [
  {name: "Peter", age: 35},
  {name: "John", age: 27},
  {name: "Jake", age: 28}
];

objs.reduce(function(accumulator, currentValue) {
  return accumulator + currentValue.age;
}, 0); // 35 + 27 + 28 = 90

Source: stackoverflow.com

Comment if you have any doubts or suggestions on this JS reduce topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading