What's the difference between transform and reduce in lodash


Other than stating "transform is a more powerful alternative to reduce", I can find no documentation of what the differences are. What are the differences between transform and reduce in lodash (Other than it being 25% slower)?

I like to dive into the source code before I pull in utilities. For lo-dash this can be difficult as there is a ton of abstracted internal functionality in all the utilities.

So the obvious differences are:

  • If you dont specify the accumulator (commonly referred to as memo if you're used to underscore), _.transform will guess if you want an array or object while reduce will make the accumulator the initial item of the collection.

Example, array or object map via transform:

_.transform([1, 2, 3], function(memo, val, idx) {
    memo[idx] = val + 5;
});
// => [6, 7, 8]

Versus reduce (note, you have to know the input type!)

_.reduce([1, 2, 3], function(memo, val, idx) {
    memo[idx] = val + 5;
    return memo;
}, []);

So while with reduce the below will compute the sum of an array, this wouldn't be possible with transform as a will be an array.

var sum = _.reduce([1, 2, 3, 4], function(a, b) {
    return a + b;
});
  • Another big difference is you don't have to return the accumulator with transform and the accumulator can't change value (ie it will always be the same array). I'd say this is the biggest advantage of the function as I've often forgotten to return the accumulator using reduce.

For example if you wanted to convert an array to dictionary of values with reduce you would write code like the following:

_.reduce([1, 2, 3, 4, 5], function(memo, idx) {
   memo[idx] = true;
   return memo;
}, {});

Whereas with transform we can write this very nicely without needing to return the accumulator like in reduce

_.transform([1, 2, 3, 4, 5], function(memo, idx) {
   memo[idx] = true;
}, {});
  • Another distinction is we can exit the transform iteration by returning false.

Overall, I'd say reduce is a more flexible method, as you have more control over the accumulator, but transform can be used to write equivalent code for some cases in a simpler style.


transform works on objects, reduce does not not