JavaScript’s Array.reduce
method is an underrated little method. Along with Array.map
and Array.filter
, it fits under the banner of ‘functional programming’, in that it lets you do things you would do with for
loops except with functions.
Array.map
maps values in one array to computed values in anotherArray.reduce
reduces values in one array into one value.
To run Array.reduce
, you’ll need:
- an array
- a function that takes arguments of
(previousValue, currentValue)
and returns a new value. - the
initialValue
Here’s sum implemented with reduce. The input array is [1, 2, 3]
, and the function adds the running sum to the current value. The starting value is 0
. The neat part is that there’s a sort of feedback loop going: what you return from the function is given back to it for the next element.
[1, 2, 3].reduce(function(sum, value) {
return sum + value;
}, 0);
Reduce feels a lot to me like making juice: you have
- the ingredients
- a function that combines the current mixture with the next ingredient
- a glass
['banana', 'cherries', 'orange'].reduce(function(juice, fruit) {
return juice + fruit;
}, empty);
Excruciating Technical Detail
Array.reduce
is underrated because it can easily implement a lot of other functions with just itself: the ‘single value’ it reduces into can be anything: a number, and array, an object, and so on…
// Array.find
function find(array, tester) {
return array.reduce(function(memo, value) {
return memo || tester(value);
}, false);
}
find([1, 2, 3], function(value) { return value > 2; });
// Array.map
function map(array, fn) {
return array.reduce(function(memo, value) {
return memo.concat([fn(value)]);
}, []);
}
map([1, 2, 3], function(value) { return value + 1; });
// Array.filter
function filter(array, fn) {
return array.reduce(function(memo, value) {
return fn(value) ? memo.concat([value]) : memo;
}, []);
}
filter([1, 2, 3], function(value) { return value > 1; });
// .length
function length(array) {
return array.reduce(function(length, value) {
return ++length;
}, 0);
}
length([1, 2, 3]);
// zip
function zip(array) {
return array.reduce(function(obj, value) {
obj[value[0]] = value[1];
return obj;
}, {});
}
zip([['foo', 'bar'], ['apples', 'grapes']]);
(live examples of these working)