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]
Supriya
  • 97
  • 3
  • 11

5 Answers5

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>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 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? – prasanth Nov 18 '16 at 10:06
  • @prasad, unique maintains the order of the items. if needed, then do a sorting afterwards. – Nina Scholz Nov 18 '16 at 10:14
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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
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)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
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.

Nakedible
  • 4,067
  • 7
  • 34
  • 40
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;});
Bardy
  • 2,100
  • 1
  • 13
  • 11