A real world reduce() example
For a long time I couldn’t think of a reasonable way to use reduce beyond the classic sum example (taken from MDN)
1 2 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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?
0