Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the lodash zip function work with an array of arrays?

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.

like image 573
Martin Burch Avatar asked Jun 30 '16 01:06

Martin Burch


People also ask

How do I merge two arrays in Lodash?

If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use. var merge = _. merge(arr1, arr2);

How do I compare two arrays of objects in Lodash?

How do you compare objects in Lodash? In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.

How do you sort an array of objects in Lodash?

The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements.

How do I get the last element of an array using Lodash?

last() method is used to get the last element of the array i.e. (n-1)th element. Parameters: This function accepts single parameter i.e. the array. Return Value: It returns the last element of the array.


1 Answers

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)
like image 53
Sean Vieira Avatar answered Oct 05 '22 23:10

Sean Vieira