DEV Community

Discussion on: Stop using for loops. Here's why.

 
idanarye profile image
Idan Arye

+1 about reduce. Consider #3 in dev.to/thejohnstew/5-programming-p...

const exampleValues = [2, 15, 8, 23, 1, 32];
const [truthyValues, falseyValues] = exampleValues.reduce((arrays, exampleValue) => {
  if (exampleValue > 10) {
    arrays[0].push(exampleValue);
    return arrays;
  }

  arrays[1].push(exampleValue);
  return arrays;
}, [[], []]);

It uses reduce to feel functional and hip, but in practice it just mutates the arrays and passing them as is (they are mutated, but it's the same reference) to the next iteration.

But even proper uses of fold/reduce are usually clearer and simpler when done with loops, because the whole point of reduce was to emulate foreach in purely functional languages.