Combining an array inside an array using lodash

How to combine arrays inside an array using lodash?

For instance:

Input:

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

Expected Result:

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

My code currently 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);
});
+4
source share
4 answers

A working answer for me, all the other answers worked, but when I checked another post, they just used loadash. I do not know what the best syntax to use for all the answers provided in the post. Now using the method below

_.uniq(_.flatten(x)); // x indicates arrayOfArrayObjects
// or, using chain
_(x).flatten().uniq().value();

Thanks to everyone for their answers. :)

+2
source

Use the method applyto pass array values ​​as arguments:

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

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

+6

, , concat:

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

...

[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
+3

reduce

arr.reduce(function(previousValue, currentValue) { 
    return previousValue.concat(currentValue);
}, []);

This will apply a callback reduction function to each element of the array and reduce it for the used example.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

+1
source

All Articles