DEV Community

Discussion on: Javascript's reduce method in a nutshell.

Collapse
 
thepeoplesbourgeois profile image
Josh • Edited

Anything for can do, reduce can do cleaner (i.e., with fewer side effects).

Getting certain items in an array:

[1, 'pears', new Set()].reduce(
  (iters, maybeIterable) => {
    if (maybeIterable[Symbol.iterator]) {
      iters.push(maybeIterable)
    }
    return iters;
  }, 
  []
);
// => [ 'pears', Set [] ]
Enter fullscreen mode Exit fullscreen mode

Transforming the contents of the array, in-place:

const words = "why would you want me to spell these words backwards".split(" ");
 words.reduce(
  (backwords, word, index) => {
    backwords[index] = word.split("").reverse().join("");
    return backwords;
  }, 
  words
)

console.log(words.join(" "))
// => yhw dluow uoy tnaw em ot lleps eseht sdrow sdrawkcab
Enter fullscreen mode Exit fullscreen mode

Summing a bunch of numbers:

// see post example
Enter fullscreen mode Exit fullscreen mode

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
*/
Enter fullscreen mode Exit fullscreen mode
Collapse
 
amiinequ profile image
Amine Amhoume

Excellent examples man! reduce() is truly powerful.

Collapse
 
kaoutharhub profile image
kaouthar-hub

can you plz add me i need to talk to you