Getting union of two arrays in JavaScript

Let's say I have an array [34, 35, 45, 48, 49] and another array [48, 55] . How can I get the resulting array [34, 35, 45, 48, 49, 55] ?

+56
javascript arrays
Sep 02 '10 at
source share
21 answers

If you don’t need to keep order and consider 45 and "45" same:

 function union_arrays (x, y) { var obj = {}; for (var i = x.length-1; i >= 0; -- i) obj[x[i]] = x[i]; for (var i = y.length-1; i >= 0; -- i) obj[y[i]] = y[i]; var res = [] for (var k in obj) { if (obj.hasOwnProperty(k)) // <-- optional res.push(obj[k]); } return res; } alert(union_arrays([34,35,45,48,49], [44,55])); // shows [49, 48, 45, 35, 34, 55, 44] 
+40
Sep 02 '10 at 18:05
source share

With the advent of ES6 with kits and the splat operator (while working only in Firefox, check the compatibility table), you can write the following critical single liner:

 var a = [34, 35, 45, 48, 49]; var b = [48, 55]; var union = [...new Set([...a, ...b])]; 

which will output something like [ 34, 35, 45, 48, 49, 55 ] .

A small explanation of this line: [...a, ...b] combines two arrays, you can also use a.concat(b) . new Set() create a set from it and therefore your union. And the last [...x] converts it back to an array.

+56
Jan 17 '15 at 7:03
source share

If you use the underscore library, you can write like this:

 _.union([34,35,45,48,49], [48,55]); // [34, 35, 45, 48, 49, 55] 

Link : http://underscorejs.org/#union

+40
May 2 '12 at 12:19
source share

I probably spend time on a dead thread. I just had to realize this and went to see if I wasted my time.

I really like KennyTM's answer. This is exactly how I will attack the problem. Combine the keys in a hash to naturally remove duplicates and then extract the keys. If you really have jQuery, you can take advantage of it to make this two-line problem and then flip it into an extension. Each () in jQuery will take care not to iterate over elements where hasOwnProperty () is false.

 jQuery.fn.extend({ union: function(array1, array2) { var hash = {}, union = []; $.each($.merge($.merge([], array1), array2), function (index, value) { hash[value] = value; }); $.each(hash, function (key, value) { union.push(key); } ); return union; } }); 

Note that both source arrays remain intact. Then you call it like this:

 var union = $.union(array1, array2); 
+16
Feb 02 '11 at 20:35
source share
 function unique(arrayName) { var newArray=new Array(); label:for(var i=0; i<arrayName.length;i++ ) { for(var j=0; j<newArray.length;j++ ) { if(newArray[j]==arrayName[i]) continue label; } newArray[newArray.length] = arrayName[i]; } return newArray; } var arr1 = new Array(0,2,4,4,4,4,4,5,5,6,6,6,7,7,8,9,5,1,2,3,0); var arr2= new Array(3,5,8,1,2,32,1,2,1,2,4,7,8,9,1,2,1,2,3,4,5); var union = unique(arr1.concat(arr2)); 
+8
02 Sep '10 at 18:01
source share

Adapted from: stack overflow

 Array.prototype.union = function(a) { var r = this.slice(0); a.forEach(function(i) { if (r.indexOf(i) < 0) r.push(i); }); return r; }; Array.prototype.diff = function(a) { return this.filter(function(i) {return a.indexOf(i) < 0;}); }; var s1 = [1, 2, 3, 4]; var s2 = [3, 4, 5, 6]; console.log("s1: " + s1); console.log("s2: " + s2); console.log("s1.union(s2): " + s1.union(s2)); console.log("s2.union(s1): " + s2.union(s1)); console.log("s1.diff(s2): " + s1.diff(s2)); console.log("s2.diff(s1): " + s2.diff(s1)); // Output: // s1: 1,2,3,4 // s2: 3,4,5,6 // s1.union(s2): 1,2,3,4,5,6 // s2.union(s1): 3,4,5,6,1,2 // s1.diff(s2): 1,2 // s2.diff(s1): 5,6 
+6
Mar 20 '14 at 2:13
source share

I like Peter Ajtai's concat-then-unique solution, but the code is not very clear. Here's a nicer alternative:

 function unique(x) { return x.filter(function(elem, index) { return x.indexOf(elem) === index; }); }; function union(x, y) { return unique(x.concat(y)); }; 

Since indexOf returns the index of the first occurrence, we check it for the current index of the element (the second parameter for the filter predicate).

+6
Aug 11 '14 at 15:52
source share

If you want to combine two arrays without any duplicate value, try this

 var a=[34, 35, 45, 48, 49]; var b=[48, 55]; var c=a.concat(b).sort(); var res=c.filter((value,pos) => {return c.indexOf(value) == pos;} ); 
+5
Jul 21 '17 at 13:10
source share

You can use jQuery plugin: jQuery Array utilities

For example, the code below

 $.union([1, 2, 2, 3], [2, 3, 4, 5, 5]) 

will return [1,2,3,4,5]

+3
Apr 25 '13 at 19:09
source share

At first I would concatenate arrays, then I would return only a unique value.

You must create your own function to return unique values. Since this is a useful feature, you can also add it as an Array functionality .

In your case with arrays array1 and array2 it will look like this:

  • array1.concat(array2) - merge two arrays
  • array1.concat(array2).unique() - return only unique values. Here unique() is the method you added to the prototype for Array .

Everything will look like this:

JsFiddle example

 Array.prototype.unique = function () { var r = new Array(); o:for(var i = 0, n = this.length; i < n; i++) { for(var x = 0, y = r.length; x < y; x++) { if(r[x]==this[i]) { continue o; } } r[r.length] = this[i]; } return r; } var array1 = [34,35,45,48,49]; var array2 = [34,35,45,48,49,55]; // concatenate the arrays then return only the unique values alert(array1.concat(array2).unique()); 
+2
Sep 02 '10 at 18:06
source share
 function unite(arr1, arr2, arr3) { newArr=arr1.concat(arr2).concat(arr3); a=newArr.filter(function(value){ return !arr1.some(function(value2){ return value == value2; }); }); console.log(arr1.concat(a)); }//This is for Sorted union following the order :) 
+2
Jul 04 '15 at 10:50
source share
 function unionArray(arrayA, arrayB) { var obj = {}, i = arrayA.length, j = arrayB.length, newArray = []; while (i--) { if (!(arrayA[i] in obj)) { obj[arrayA[i]] = true; newArray.push(arrayA[i]); } } while (j--) { if (!(arrayB[j] in obj)) { obj[arrayB[j]] = true; newArray.push(arrayB[j]); } } return newArray; } unionArray([34, 35, 45, 48, 49], [44, 55]); 

Faster http://jsperf.com/union-array-faster

+1
Oct 12
source share
 function unionArrays() { var args = arguments, l = args.length, obj = {}, res = [], i, j, k; while (l--) { k = args[l]; i = k.length; while (i--) { j = k[i]; if (!obj[j]) { obj[j] = 1; res.push(j); } } } return res; } 

Somewhat similar in approach to the alejandro method, but a little shorter and should work with any number of arrays.

+1
Feb 11 '13 at 21:57
source share

Just wrote earlier for the same reason (works with any number of arrays):

 /** * Returns with the union of the given arrays. * * @param Any amount of arrays to be united. * @returns {array} The union array. */ function uniteArrays() { var union = []; for (var argumentIndex = 0; argumentIndex < arguments.length; argumentIndex++) { eachArgument = arguments[argumentIndex]; if (typeof eachArgument !== 'array') { eachArray = eachArgument; for (var index = 0; index < eachArray.length; index++) { eachValue = eachArray[index]; if (arrayHasValue(union, eachValue) == false) union.push(eachValue); } } } return union; } function arrayHasValue(array, value) { return array.indexOf(value) != -1; } 
+1
Jan 05 '14 at 2:07
source share

An easy way to handle combining the values ​​of a single array.

 var values[0] = {"id":1235,"name":"value 1"} values[1] = {"id":4323,"name":"value 2"} var object=null; var first=values[0]; for (var i in values) if(i>0) object= $.merge(values[i],first) 
+1
Feb 05 '15 at 22:38
source share

You can try:

 function union(a, b) { return a.concat(b).reduce(function(prev, cur) { if (prev.indexOf(cur) === -1) prev.push(cur); return prev; }, []); } 

or

 function union(a, b) { return a.concat(b.filter(function(el) { return a.indexOf(el) === -1; })); } 
+1
Mar 12 '15 at 4:58
source share

A shorter version of kennith's answer:

 function unionArrays(a, b) { const cache = {}; a.forEach(item => cache[item] = item); b.forEach(item => cache[item] = item); return Object.keys(cache).map(key => cache[key]); }; 
+1
Nov 12 '16 at 0:30
source share

I think it would be easier to create a new array by adding unique values ​​only by the definition of indexOf.

This seems to me the easiest solution, although I do not know if it is the most effective. Sort is not saved.

 var a = [34, 35, 45, 48, 49], b = [48, 55]; var c = union(a, b); function union(a, b) { // will work for n >= 2 inputs var newArray = []; //cycle through input arrays for (var i = 0, l = arguments.length; i < l; i++) { //cycle through each input arrays elements var array = arguments[i]; for (var ii = 0, ll = array.length; ii < ll; ii++) { var val = array[ii]; //only add elements to the new array if they are unique if (newArray.indexOf(val) < 0) newArray.push(val); } } return newArray; } 
0
Sep 16 '14 at 3:03
source share
 [i for( i of new Set(array1.concat(array2)))] 

Let me break it down for you

 // This is a list by comprehension // Store each result in an element of the array [i // will be placed in the variable "i", for each element of... for( i of // ... the Set which is made of... new Set( // ...the concatenation of both arrays array1.concat(array2) ) ) ] 

In other words, it first combines both, and then removes duplicates (a set, by definition, cannot have duplicates)

Please note, however, that the order of the elements is not guaranteed in this case.

0
Nov 06 '14 at 17:14
source share

ES2015 Version

 Array.prototype.diff = function(a) {return this.filter(i => a.indexOf(i) < 0)}; Array.prototype.union = function(a) {return [...this.diff(a), ...a]} 
0
Sep 16 '16 at 4:12
source share

If you want the custom equals function to match your elements, you can use this function in ES2015:

 function unionEquals(left, right, equals){ return left.concat(right).reduce( (acc,element) => { return acc.some(elt => equals(elt, element))? acc : acc.concat(element) }, []); } 

It moves along the left / right array. Then for each cell it will fill the battery if it does not find this cell in the battery. At the end there is no duplicate specified by the equals function.

Pretty, but probably not very effective with thousands of objects.

0
Oct 23 '17 at 10:41 on
source share



All Articles