Yes it can but that doesn't mean that you should swap Array#map
for Array#reduce
for any single task.
If you meant to transform all items in an array, then Array#map
is just more practical:
[1,2,3].map(x => x + 10);
//=> [11,12,13]
// vs
[1,2,3].reduce((acc, x) => (acc.push(x + 10), acc), []);
//=> [11,12,13]
The canonical example for Array#reduce
is to reduce a list to a single value. e.g., summing up the numbers in a list:
[1,2,3].reduce((tot, x) => tot + x, 0);
//=> 6
If you meant to transform and filter at the same time then Array#reduce
may be helpful:
[1,true,2,false,3].filter(x => typeof x === 'number').map(x => x + 10);
//=> [11,12,13]
// vs
[1,true,2,false,3].reduce((acc, x) =>
typeof x === 'number' ? (acc.push(x + 10), acc) : acc, []);
//=> [11,12,13]
Syntactically it could be argued that the .filter().map()
approach looks prettier but it does iterate more than necessary: .filter()
yields another array for .map()
to consume.
If you have a big list to process, chaining array operations ala jQuery may be inefficient:
[items × 1000].filter(...).map(...).filter(...).map(...).filter(...);
// Depending on what you do at each step this could take a while