Anything for can do, reduce can do cleaner (i.e., with fewer side effects).
Getting certain items in an array:
[1,'pears',newSet()].reduce((iters,maybeIterable)=>{if(maybeIterable[Symbol.iterator]){iters.push(maybeIterable)}returniters;},[]);// => [ 'pears', Set [] ]
Transforming the contents of the array, in-place:
constwords="why would you want me to spell these words backwards".split("");words.reduce((backwords,word,index)=>{backwords[index]=word.split("").reverse().join("");returnbackwords;},words)console.log(words.join(""))// => yhw dluow uoy tnaw em ot lleps eseht sdrow sdrawkcab
Summing a bunch of numbers:
// see post example
Even mimicking forEach(), if you hate optimized native code:
['butter','milk','eggs','whatever'].reduce((_,item)=>console.log(item),null// if no accumulator is passed, the first item in the list won't be logged)/*
butter
milk
eggs
whatever
=> undefined
*/
Anything
for
can do,reduce
can do cleaner (i.e., with fewer side effects).Getting certain items in an array:
Transforming the contents of the array, in-place:
Summing a bunch of numbers:
Even mimicking
forEach()
, if you hate optimized native code:Excellent examples man! reduce() is truly powerful.
can you plz add me i need to talk to you