michelle
michelle

Reputation: 23

Difference usage between reduce and reduceRight w Underscore.js

I'm a newbie with Underscore.js.

Recently I read the documentation about reduce and reduceRight but I couldn't understand what is the difference between the two.

I will appreciate any help and example.

Upvotes: 1

Views: 603

Answers (1)

idbehold
idbehold

Reputation: 17168

Well, _.reduce iterates over the collection starting at the first index and finishing on the last index while _.reduceRight does the same thing but starts at the last index and finishes on the first index.

var list = ['a', 'b', 'c'];
_.reduce(list, function(memo, item) { memo.push(item); return memo; }, []);
=> ['a', 'b', 'c']
_.reduceRight(list, function(memo, item) { memo.push(item); return memo; }, []);
=> ['c', 'b', 'a']

Upvotes: 5

Related Questions