4

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?

3
  • 1
    Why do you need to use reduce like this? IF you need to clone an array you'wd better just slice it. Commented Jan 22, 2012 at 6:55
  • Seriously, this would be much better done as myArray.slice() Commented Jan 22, 2012 at 7:39
  • Well... It's example. I was actually trying to sort an array into groups which, yes, I know could be done with _.sortBy(). Functionally speaking map and reduce are the building blocks of the other more complicated list comprehension functions. So my question looks to understand why reduce was not returning a list, which was my first step to making a sort into groups using only reduce. Commented Jan 24, 2012 at 3:40

1 Answer 1

14

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; }, []);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.