What's the difference between transform and reduce in lodash

痞子三分冷 提交于 2019-12-20 08:46:54

问题


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)?


回答1:


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.

  • transform source
  • reduce source

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.




回答2:


transform works on objects, reduce does not not



来源:https://stackoverflow.com/questions/21536627/whats-the-difference-between-transform-and-reduce-in-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!