JavaScript Answers

How to call JavaScript reduce() on an object?

Spread the love

To call JavaScript reduce() on an object, we can use the Object.values method.

For instance, we write

const o = {
  a: { value: 1 },
  b: { value: 2 },
  c: { value: 3 },

Object.values(o).reduce((previous, entry) => {
  return previous + entry.value;
}, 0);

to call Object.values with o to return an array of object property values in o.

Then we call reduce with a callback that returns the sum of the previous partial sum plus the entry.value value.

entry is the o property value being looped through.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.