Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of array inside array using lodash

How can I union arrays inside an array using lodash?

For example:

Input:

var x = [ [1,2,3,4], [5,6,7], [], [8,9], [] ];

Expected output:

x = [1,2,3,4,5,6,7,8,9];

Currently my code does the following:

return promise.map(someObjects, function (object)) {
    return anArrayOfElements();
}).then(function (arrayOfArrayElements) {
    // I tried to use union but it can apply only on two arrays
    _.union(arrayOfArrayElements);
});
like image 687
user2936008 Avatar asked May 18 '16 23:05

user2936008


2 Answers

Use apply method to pass array values as arguments:

var union = _.union.apply(null, arrayOfArrayElements);

[ https://jsfiddle.net/qe5n89dh/ ]

like image 102
stdob-- Avatar answered Oct 06 '22 00:10

stdob--


The simplest solution I can think of is to just use concat:

Array.prototype.concat.apply([], [ [1,2,3,4], [5,6,7],[], [8,9], []]);

Will produce...

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
like image 43
David Johnson Avatar answered Oct 05 '22 23:10

David Johnson