Categories
JavaScript Answers

How to Call Javascript Array’s reduce Method on an Array of Objects?

Spread the love

Sometimes, we’ve to call the JavaScript array’s reduce method on an array of objects and we want to get a result from it.

In this article, we’ll look at how to JavaScript array’s reduce method to produce a result and put it in an object.

Calling reduce on an Array of Objects

To call reduce on an array of objects, we can get the object from the callback.

To do this, we write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((a, b) => ({
  x: a.x + b.x
}));
console.log(result)

We have the arr array.

And we call reduce on it with a callback by returning an object with the x property and the x property from a and b added together.

a and b are the objects that are from the arr array.

We can also get the value of the x property and just add them together.

For instance, we can write:

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

acc is the sum of all the x property values together.

obj has the object in arr that we’re iterating through.

We return acc + obj.x to return the sum.

The 2nd argument is the initial value of the returned result.

We set it to 0 so that we can add the x values together.

And so result is 6.

Also, we can destructure the object in the 2nd parameter of the callback by writing:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.reduce((acc, { x }) => {
  return acc + x;
}, 0);
console.log(result)

Using map and reduce Together

Also, we can use the map and reduce methods together.

We use map to return an array of numbers from the x property.

And then we can use reduce to add all the numbers together.

For instance, we can write:

const arr = [{
  x: 1
}, {
  x: 2
}, {
  x: 3
}];
const result = arr.map((a) => a.x)
  .reduce((a, b) => a + b);
console.log(result)

We call map with a callback to return the value of x .

And then we call reduce with a callback to return the sum.

Conclusion

We can call reduce on an array of objects by getting the object from the parameter and do what we want with it.

Or we can use map to extract the values we want from the array entries and call reduce to combine the values the way we want.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *