How to Reduce an Array of Objects in JavaScript

To reduce an array of objects in JavaScript, you can use the “array.reduce()” method. The array.reduce() method is “used to reduce an array of objects to a single value by executing a callback function for each array element”.

Syntax

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Parameters

function: It is a callback function.

  1. total: It is the function’s initial value or the previously returned value.
  2. currentValue: It is the value of the current item in an array.
  3. currentIndex: It is the index of the current element.
  4. arr: It is the array object to which the current element belongs.
  5. initialValue: It is a value to be passed to the function as the initial value.

Return value

The value results from running the “reducer” callback function to completion over the entire array.

Example

const mainArray = [
 { values: 21 },
 { values: 19 },
 { values: 46 }
];

// A callback function that adds up two values
const addValues = (total, currentValue) => {
  return total + currentValue.values;
};

// Using reduce() to get the sum of all values
const sum = mainArray.reduce(addValues, 0); // Initial value is 0

console.log(sum);

Output

86

That’s it.

1 thought on “How to Reduce an Array of Objects in JavaScript”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.