1

I have below array format and i want to make union of it using lodash or normal js.

var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]

I want to make union of all these into one and output should be below array.

testArray  = [1,2,3,4,5,6,7,8,9,10]
5

5 Answers 5

2

You could combine flattenDeep with _.union. If needed apply sorting

var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]],
    result = _.chain(testArray)
             .flattenDeep()
             .union();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

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

2 Comments

i dn't why OP want make a array like [1,2,3,4,5,6,7,8,9,10] .but your answer like [1,2,3,4,5,6,7,8,10,9] .why last two number was swap? is right or wrong?
@prasad, unique maintains the order of the items. if needed, then do a sorting afterwards.
2

Apply _.union() to the parent array:

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

var result = _.union.apply(_, testArray);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Or use array spread if ES6 is supported:

const testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]];

const result = _.union(...testArray);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

Comments

1

With ES6 you can do this using spread syntax ... and Set

var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]

var result = [...new Set([].concat(...testArray))];
console.log(result)

Comments

0

You can just call _.union.apply(null, arrays). It is documented here:

https://lodash.com/docs/#union

> var testArray = [[1,2,3,4,5,6,7,8],[1,2,3,4,5,10,7,8],[1,2,3,6,7,8],[9],[3,4,5]]
> lodash.union.apply(null, testArray)
[ 1, 2, 3, 4, 5, 6, 7, 8, 10, 9 ]

The apply trick is to transform your array of array in to function call arguments. If you need it sorted as well, you can just tuck .sort() at the end of it.

Comments

0

In just ES5 if you need that:

var flattened = Object.keys(testArray.reduce(function(acc, cur) {
  cur.forEach(function(v) {acc[v] = true;});
  return acc;
}, {})).sort(function(a, b) {return a - b;});

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.