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)?
Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. reduce() method reduces collection to value which is accumulated result of running each element in the collection through iteratee, where each successive invocation is supplied return value of the previous.
Lodash is a popular javascript based library which provides 200+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.
Lodash is one of those handful of libraries, that were created to solve a growing problem, that fortunately due to Microsoft's foresight, no longer exists.
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:
_.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;
});
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;
}, {});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With