making juice with Array.reduce

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.

To run Array.reduce, you’ll need:

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

['banana', 'cherries', 'orange'].reduce(function(juice, fruit) {
  return juice + fruit;
}, empty);

making juice with Array.reduce

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)

See Also

Posted Jan 03, 2015 Tweet / Follow me on Twitter

Write JavaScript? I've written many other articles on the topic.

Tom MacWright

I'm . I work on tools for creativity at Mapbox. This is where I write about technology and everything else.