You don't need Array.reduce()
Joe Pea
Posted on September 22, 2018
I was reading another dev.to post, Demystifying Array.reduce()
, but I didn't feel convinced about using Array.reduce()
.
Maybe I too am not using Array.reduce()
the right way, but every time I do, I end up disliking it and switching to a simple for..of
loop.
Up ahead are the three examples from that article, converted to use for..of
and in my opinion easier to read and cleaner.
Take for example the sum example:
const array = [1, 2, 3, 4];
const sum = array.reduce((accumulator, currentItem) => {
return accumulator + currentItem;
}, 0);
// sum = 10
It can be written as
const array = [1, 2, 3, 4]
let sum = 0
for (const n of array) sum += n
// sum = 10
That's simpler!
The next example,
const trips = [{type: 'car', dist: 42}, {type: 'foot', dist: 3}, {type:'flight', dist: 212}, {type: 'car', dist: 90}, {type: 'foot', dist: 7}]
const distanceByType = trip.reduce((out, curr) => {
const { type, dist } = curr;
if (out[type]) {
out[type] += dist;
} else {
out[type] = dist;
}
return out;
}, {});
// distanceByType = {car: 132, foot: 10, flight: 212};
can be rewritten as
const trips = [{type: 'car', dist: 42}, {type: 'foot', dist: 3}, {type:'flight', dist: 212}, {type: 'car', dist: 90}, {type: 'foot', dist: 7}]
const distanceByType = {}
for (const trip of trips) {
const { type, dist } = trip
if (distanceByType[type]) {
distanceByType[type] += dist
} else {
distanceByType[type] = dist
}
}
// distanceByType = {car: 132, foot: 10, flight: 212}
Simple!
Finally, the example from the comments about piping functions,
const pipeOnce = (fn1, fn2) => (args) => (fn2(fn1(args)));
const pipe = (...ops) => ops.reduce(pipeOnce);
const addTwo = a => a + 2;
const mulTwo = a => a * 2;
const addTwoMulTwo = pipe(addTwo, mulTwo);
console.log(addTwoMulTwo(1)); // (1 + 2) * 2 => 6
console.log(addTwoMulTwo(2)); // (2 + 2) * 2 => 8
console.log(addTwoMulTwo(3)); // (3 + 2) * 2 => 10
is a better of example of reduce, but it can be written as
const addTwo = a => a + 2;
const mulTwo = a => a * 2;
const addTwoMulTwo = n => mulTwo(addTwo(n))
console.log(addTwoMulTwo(1)); // (1 + 2) * 2 => 6
console.log(addTwoMulTwo(2)); // (2 + 2) * 2 => 8
console.log(addTwoMulTwo(3)); // (3 + 2) * 2 => 10
If we want to pipe an arbitrary number of functions, we can do it with for..of
too:
const pipe = (...fns) => arg => {
for (const fn of fns) arg = fn(arg)
return arg
}
const addTwoMulTwo = pipe(addTwo, mulTwo)
This one isn't as short, but it is easier to understand.
What are some use cases where Array.reduce()
really shines over alternatives like for..of
?
Please share if you know!
Posted on September 22, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.