5

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);
});
3
  • Have you tried _.flatten? Commented May 18, 2016 at 23:50
  • yep worked just now .union(.flatten(x)) Commented May 18, 2016 at 23:56
  • 1
    Check out the example "Flatten an array of arrays" in developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. It does exactly what you want :D Commented May 18, 2016 at 23:58

4 Answers 4

6

Use apply method to pass array values as arguments:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

why are we passing null as parameter ?
Because we do not need to pass this (see. apply definition).
3

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 ]

2 Comments

Concat not remove duplicate items instead lodash union.
Ah, I missed that it should remove dupes.
3

Worked answer for me , all other answers worked but when i checked other post they simply used loadash. I dnt know what is the best syntax to use for all the answers provided in the post. For now using the below method

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

Thanks everyone for their answers. :)

Comments

1

Just reduce it using the native function reduce

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

This will apply the reduce callback function to each element of the array and reduce it for the use case you have shown.

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

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.