DEV Community

Discussion on: How reduce() function really works

Collapse
 
devhammed profile image
Hammed Oyedele • Edited

Are you sure that is how it truly works, what if my accumulator is not a number? do you know you can implement map and filter Array functions using reduce?

reduce

I think a better representation will be:

  function reduce (arr, fn, accumulator = 0) {
    arr.forEach((item, index) => {
      accumulator = fn(accumulator, item, index) // set the current accumulator value to the return value of the function
    })
    return accumulator
  }
Enter fullscreen mode Exit fullscreen mode

And welcome to Dev.together 🥰🥰🥰

Collapse
 
saucekode profile image
Chiamaka Mbah

Thank you for this but really I just wanted to let beginners see what the reduce() looks like behind the scene. But truly, thank you. 🤗