11

The lodash zip() function normally accepts two or more arrays as arguments. Can it accept an array of arrays?

For example, given an object like var aa = [[1,2,3],[4,5,6]]; and a desired output of [[1,4],[2,5],[3,6]] zip() must be called like _.zip(aa[0],aa[1]). For an array of arrays with more than two elements, typing the indexes into the function call becomes repetitive.

Calling _.zip(aa) doesn't work. It just nests the original array of arrays.

2 Answers 2

12

You can splat your array of arrays using apply or the ES2015 spread operator (...):

// call zip with a `this` context of the lodash object
// and with each entry in aa as a separate argument
// e. g. zip(aa[0], aa[1], ..., aa[N]);
_.zip.apply(_, aa);

// Same call, but using ES2015
_.zip(...aa)
Sign up to request clarification or add additional context in comments.

1 Comment

This is an important note about the right context to pass. It might sometimes work to pass null but the lodash object is the obviously right choice.
3

Sure, try this:

_.zip.apply(_, aa)

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.