Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using underscore.js can reduce return an array?

I'm trying to use reduce to return an array like so:

var myArray = [1,2,3];
_.reduce(myArray, function (seed, item) { return seed.push(item);}, []);

I expect that it will produce an array just like myArray. Instead for the first item, seed is an array. Then for the second item, seed is a number. That causes an error and the third item is never reached.

Whats happening here?

like image 343
QueueHammer Avatar asked Dec 09 '22 03:12

QueueHammer


1 Answers

Actually, seed.push() does not return the modified seed. Do the following, and it's right:

_.reduce(myArray, function (seed, item) { seed.push(item); return seed; }, []);
like image 84
Sajid Avatar answered Dec 26 '22 12:12

Sajid