You can call JavaScript array’s reduce()
method on an array of objects by passing a callback function as the first argument to reduce()
. The callback function should take two parameters: an accumulator and the current value of the array. In the case of an array of objects, the current value is an object.
Here’s an example of how you can use reduce()
to sum the values of a property in an array of objects:
const arrayOfObjects = [
{ id: 1, value: 10 },
{ id: 2, value: 20 },
{ id: 3, value: 30 }
];
const sum = arrayOfObjects.reduce((accumulator, current) => {
return accumulator + current.value;
}, 0);
console.log(sum); // Output: 60
In this example, the reduce()
method is called on the arrayOfObjects
array. The callback function takes two parameters: accumulator
and current
. The accumulator
is initialized to 0
as the second argument to reduce()
.
On each iteration, the current
parameter is an object from the array. The callback function returns the sum of the accumulator
and the value of the value
property of the current
object.
The final value of the accumulator
is the sum of all the value
properties of the objects in the array, which is logged to the console.
You can also use reduce()
to transform an array of objects into a new object or array. The callback function can return any value, not just a number.
+ There are no comments
Add yours