Playing with array.reduce()



// I think "accumulated" is a better name than "accumulator". 
// This arg is the value that's been accumulated, not a
// long-lasting a thing that accumulates stuff.

let arr = [11,22,33]
arr.reduce((accumulated, current)=>(accumulated + current))
>>66

// The first call to your function uses the first AND SECOND array elements
arr.reduce((accumulated, current)=>{console.log(accumulated + ' ' + current); return 'hi'})
  11 22
  hi 33
>>"hi"

// ...unless you provide a second arg to Array.reduce itself. If you do, then 
// that second arg will be passed as accumulated on the first call of your function.
// And that also means that the first call no longer consumes two elements.
arr.reduce((accumulated, current)=>{console.log(accumulated + ' ' + current); return 'hi'}, 1000)
  1000 11
  hi 22
  hi 33
>>"hi"

// Using the second arg is safer. Without it, and empty array does this:
arr = []
arr.reduce((accumulated, current)=>(accumulated + current))
>> Uncaught TypeError: Reduce of empty array with no initial value

//...but now we're ok
arr.reduce((accumulated, current)=>(accumulated + current), 0)
>>0

// If there's exactly one value available, because either array.length==1 or because the
// array was empty but the second argument was provided, then that one value is just returned
// without calling your function.
let bobTheObj = {}
let empty = []
let result = empty.reduce((accumulated, current)=>{console.log('Never!'); return 555}, bobTheObj)
result === bobTheObj
>>true 

// By starting with an object and always returning that object, the "accumulat..." arg
// can actually be a thing that accumulates.
arr = [11,22,33]
arr.reduce((accumulator, current)=>{accumulator.unshift(current); return accumulator}, [])
>>[33, 22, 11]

//There are actually four args
//  accumulat__
//  current
//  currentIndex
//  theOriginalArray

let toDos = ['take out trash', 'brush cat', 'clean fusion reactor']
toDos.reduce((accumulated, current, index)=>(accumulated + index + ' ' + current + '\n'), '')
>> "0 take out trash
1 brush cat
2 clean fusion reactor
"


Comments

Popular posts from this blog

Callback, Promise, Observable, and Doughnuts

Learn grid and grid-template-areas FIRST!!!

The Day TDD Started Working for Me