A real world reduce() example

Posted on Wednesday, November 20th, 2019

For a long time I couldn’t think of a way to use reduce beyond the classic sum example (taken from MDN)

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => 
  accumulator + currentValue;

A few days ago, I found a way to make reduce() actually useful to me. I have been using to create a new array out of an array of objects.

I had an array of complex objects, and I wanted to just get an array containing one of those properties.

const people = [
  {
    id: 1,
    entries: [{name: 'Peach'}, {name: 'Mario'}]
  },
  {
    id: 2,
    entries: [{name: 'Bowser'}]
  }
]

const reducer = (acc, current) => {
  return [...acc, ...current.entries]
}

const names = people.reduce(reducer, [])

console.log(names) // [{name: 'Peach'}, {name: 'Mario'}, {name: 'Bowser'}]

Not sure why I never thought of this before, but better late than never, right?