A real world reduce() example

Posted on Wed, 20 Nov 2019 08:32:28 GMT
JavaScript

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 it 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, the name.

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?


Photo by Kaidi Guo on Unsplash