DEV Community

Discussion on: .map(), .filter(), and .reduce()

Collapse
 
astromium profile image
Ayoub Belouadah

I still dont get the .reduce() πŸ˜”

Collapse
 
pickleat profile image
Andy Pickle

That’s ok! It took me a long time to get it. Reduce is useful because you get a single value returned from an array of values. For example, if you have an array and you need to total of all the numbers.

The accumulator is just the total up to that point and the currentValue is just the value at whatever index you are currently at. So if you are adding, it’ll be the total + the value and then repeat until it’s gone through every number in the array and return the value of the last operation. Hope this helps! Try playing with the MDN examples they may help too!

Collapse
 
mateiadrielrafael profile image
Matei Adriel • Edited

Since you understand map but don't understand reduce, implementing map with reduce might help:

const map = (arr, func) => arr.reduce((acc, curr) => [...acc, func(curr)], [])

Edit: here's the same for filter:

const filter = (arr, func) => arr.reduce((acc, curr) => func(curr) ? [...acc, curr] : acc, [])