re: Explain REDUCE Like I'm Five VIEW POST

FULL DISCUSSION
 

You can use reduce anywhere you could use a for or forEach loop. The main thing to understand about it is that what you return within it will be held onto for the next iteration, until you get through the entire collection you're reducing. You can actually implement map, filter, and forEach as variations of reduce, if you want to!

const map = (iterable, fn) => [...iterable].reduce((arr, item) => {
  arr.push(fn(item))
  return arr
}, [])

const filter = (iterable, fn) => [...iterable].reduce((arr, item) => {
  if (fn(item)) arr.push(item)
  return arr
}, [])

const forEach = (iterable, fn) => [...iterable].reduce((_, item) => { fn(item) }, null)

The most common example of a reduce is to sum a bunch of numbers, but you can also use it to join things as strings …

const join = (arr, separator = ",") => 
  arr.reduce((string, item, index) => string + 
    `${typeof item === "object" ? JSON.stringify(item) : item}` + 
    (index === arr.size - 1 ? "" : separator)
  )

Or you can use it to do a simple (naïve) reverse!

const reverse = (iter) => [...iter].reduce((rev, item) => {
  rev.unshift(item)
  return rev
}, [])

The essential thing to remember: reduce is basically for, only more FP about it.

code of conduct - report abuse