Write a javascript program to compute the union of two arrays

Say I have an array of [34, 35, 45, 48, 49] and another array of [48, 55]. How can I get a resulting array of [34, 35, 45, 48, 49, 55]?

crdx

1,41211 silver badges26 bronze badges

asked Sep 2, 2010 at 17:58

2

With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:

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

Little explanation about this line: [...a, ...b] concatenates two arrays, you can use a.concat(b) as well. new Set() create a set out of it and thus your union. And the last [...x] converts it back to an array.

answered Jan 17, 2015 at 7:03

Salvador DaliSalvador Dali

204k142 gold badges686 silver badges746 bronze badges

4

If you don't need to keep the order, and consider 45 and "45" to be the 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;
}

console.log(union_arrays([34,35,45,48,49], [44,55]));

answered Sep 2, 2010 at 18:05

kennytmkennytm

498k101 gold badges1061 silver badges994 bronze badges

6

If you use the library underscore you can write like this

var unionArr = _.union([34,35,45,48,49], [48,55]);
console.log(unionArr);

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

answered May 2, 2012 at 12:19

CodlerCodler

10.6k6 gold badges51 silver badges65 bronze badges

2

I'm probably wasting time on a dead thread here. I just had to implement this and went looking to see if I was wasting my time.

I really like KennyTM's answer. That's just how I would attack the problem. Merge the keys into a hash to naturally eliminate duplicates and then extract the keys. If you actually have jQuery you can leverage its goodies to make this a 2 line problem and then roll it into an extension. The each() in jQuery will take care of not iterating over items 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 of the original arrays are left intact. Then you call it like this:

var union = $.union(array1, array2);

answered Feb 2, 2011 at 20:35

4

If you wants to concatenate two arrays without any duplicate value,Just 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;} );

answered Jul 21, 2017 at 13:10

3

function unique(arrayName)
{
  var newArray=new Array();
  label: for(var i=0; i

answered Sep 2, 2010 at 18:01

BobBob

3,05411 gold badges42 silver badges62 bronze badges

10

Adapted from: https://stackoverflow.com/a/4026828/1830259

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 

answered Mar 20, 2014 at 2:13

Adam FoxAdam Fox

3,4385 gold badges22 silver badges20 bronze badges

I like Peter Ajtai's concat-then-unique solution, but the code's 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 occurence, we check this against the current element's index (the second parameter to the filter predicate).

answered Aug 11, 2014 at 15:52

WarboWarbo

2,5221 gold badge28 silver badges21 bronze badges

Shorter version of kennytm'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]);
};

answered Nov 12, 2016 at 0:30

Write a javascript program to compute the union of two arrays

You can use a 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]

answered Apr 25, 2013 at 19:09

1

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 :)

answered Jul 4, 2015 at 10:50

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;
}
var unionArr = unionArrays([34, 35, 45, 48, 49], [44, 55]);
console.log(unionArr);

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

answered Feb 11, 2013 at 21:57

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;
}
var unionArr = unionArray([34, 35, 45, 48, 49], [44, 55]);
console.log(unionArr);

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

answered Oct 12, 2012 at 0:40

alejandroalejandro

2,7811 gold badge16 silver badges25 bronze badges

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

You have to create your own function to return unique values. Since it is a useful function, you might as well add it in as a functionality of the Array.

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

  1. array1.concat(array2) - concatenate the two arrays
  2. array1.concat(array2).unique() - return only the unique values. Here unique() is a method you added to the prototype for Array.

The whole thing would look like this:

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
console.log(array1.concat(array2).unique());

answered Sep 2, 2010 at 18:06

Peter AjtaiPeter Ajtai

56.1k13 gold badges120 silver badges139 bronze badges

1

Just wrote before for the same reason (works with any amount 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; }

answered Jan 5, 2014 at 2:07

Write a javascript program to compute the union of two arrays

Geri BorbásGeri Borbás

15.2k17 gold badges104 silver badges167 bronze badges

Simple way to deal with merging single array values.

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)

Write a javascript program to compute the union of two arrays

Machavity

30.1k26 gold badges87 silver badges98 bronze badges

answered Feb 5, 2015 at 22:38

Write a javascript program to compute the union of two arrays

You can try these:

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;
    }));
}

answered Mar 12, 2015 at 4:58

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]}

answered Sep 16, 2016 at 4:12

Write a javascript program to compute the union of two arrays

Adnan YAdnan Y

2,6521 gold badge23 silver badges28 bronze badges

4

If you want a 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 traverses the left+right array. Then for each element, will fill the accumulator if it does not find that element in the accumulator. At the end, there are no duplicate as specified by the equals function.

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

answered Oct 23, 2017 at 10:41

Write a javascript program to compute the union of two arrays

Nicolas ZozolNicolas Zozol

6,9653 gold badges50 silver badges72 bronze badges

I think it would be simplest to create a new array, adding the unique values only as determined by indexOf.

This seems to me to be the most straightforward solution, though I don't know if it is the most efficient. Collation is not preserved.

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;
}

answered Sep 16, 2014 at 3:03

supershneesupershnee

1,1961 gold badge13 silver badges13 bronze badges

0

[i for( i of new Set(array1.concat(array2)))]

Let me break this into parts 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 concatenates both and then it removes the duplicates (a Set, by definition cannot have duplicates)

Do note, though, that the order of the elements is not guaranteed, in this case.

answered Nov 6, 2014 at 17:14

brunoaisbrunoais

5,6608 gold badges36 silver badges58 bronze badges

0

How do you find the union of two arrays?

To find union of two sorted arrays, follow the following merge procedure :.
Use two index variables i and j, initial values i = 0, j = 0..
If arr1[i] is smaller than arr2[j] then print arr1[i] and increment i..
If arr1[i] is greater than arr2[j] then print arr2[j] and increment j..

What is a union in JavaScript?

union() function is used to take n number of arrays and return a new array with the unique terms in all those arrays (union of all array). It scrutinizes each and every value of the arrays and pushes out unique values into another array.

How do you create a set of two arrays?

To get a union of two arrays: Use the spread operator (...) to merge the arrays into a third array. Pass the third array as a parameter to the Set constructor to remove the duplicates. Convert the Set back to an array.

Which function finds difference between two arrays?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.