50

I have two arrays in javascript -:

var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];

I need to a method to get the unique from two arrays and put them in array3 Array3 should be -:

var array3 = ['1','100'];

Thanks for help.

1
  • Please, have a look at the underscore.js documentation. The library provides a lot of objects and arrays utilities and is available client and server side. Commented Apr 9, 2013 at 21:17

7 Answers 7

66
var array3 = array1.filter(function(obj) { return array2.indexOf(obj) == -1; });

MDN on Array#filter: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

Includes a polyfill for older browsers.

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

6 Comments

This results in o(n^2) complexity which will become quite slow when processing large arrays.
But hopefully, i am not gonna have such big array to result in o(n^2) complexity. Thanks
If there are any values in array2 that do not exist in array1, then it will not show. For example var array1 = [1,3,5,7,9]; var array2 = [1,2,3,5,100]; will result in [7, 9] instead of [2,7,9,100]
You need to check the other way around too. This answer isn't correct.
this will not include second array, @Hedley Smith's answer
|
30

With a bit of ES6 magic it can be fairly concise. Note that we need to check both ways around in case there are unique items in either array.

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 3, 8];

let unique1 = arr1.filter((o) => arr2.indexOf(o) === -1);
let unique2 = arr2.filter((o) => arr1.indexOf(o) === -1);

const unique = unique1.concat(unique2);

console.log(unique);
// >> [2, 4, 5, 8]

2 Comments

If arr2 contains an unique number, then it will not be added to unique.
@curly_brackets - thanks, edited! Not quite so concise now, there's probably a more terse way of doing this but this is pretty readable at least.
8
var unique = [];
for(var i = 0; i < array1.length; i++){
    var found = false;

    for(var j = 0; j < array2.length; j++){ // j < is missed;
     if(array1[i] == array2[j]){
      found = true;
      break; 
    }
   }
   if(found == false){
   unique.push(array1[i]);
  }
}

UPDATE The original post works but is not very fast, this implementation is a lot faster, this example uses only one array, but in the function you can easily pass any additional arrays to combine.

only a simple error check is done and more should be in place, use at own discretion, meant as working example only.

function Unique(array) {
var tmp = [];
var result = [];

if (array !== undefined /* any additional error checking */ ) {
  for (var i = 0; i < array.length; i++) {
    var val = array[i];

    if (tmp[val] === undefined) {
       tmp[val] = true;
       result.push(val);
     }

    }
  }

  return result;
}

var unique = Unique([1, 2, 2, 6, 8, 5, 6, 8]);

Additionally this can be implemented as prototype of the Array object, changing the signature to

Array.prototype.Unique = function() {
    var array = this;
    ...
}

and can be called like this:

var unique = [1, 2, 2, 6, 8, 5, 6, 8].Unique();

2 Comments

I did this, but my code is pretty slow. Is there an optimal way?
@SterlingDiaz if your values are all positive, yes you can optimize it by using the values as indexes in another array, so only the values set are unique
2

Something like this

var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];
var o = {};
for(var i in array1) {
    o[i] = 1;
}
for(var i in array2) {
    o[i] = 0;
}
var array3 = [];
for(var i in o) {
    if(o[i] == 1) {
        array3.push(i);
    }
}

3 Comments

There is a more generic answer here: stackoverflow.com/questions/8628059/…
Does not work if array 1 has unique values that array 2 does not.
Yes. My solution is not symmetric. The original question isn't totally clear whether that is a requirement or not.
1
var array3 = array1.concat(array2);

array3 = array3.sort(function(a, b) { return a > b; });
array3 = array3.filter(function(num, index) { return num !== array3[index + 1]; });

array3 will have only unique values

this also does the job in two loops which is pretty inexpensive, it should be noted that sort() and filter() are ECMA5 functions and not supported in older browsers, also i usually use a library like underscore so i don't have rewrite these functions for each project i work on, underscore has a .unique() method which obviously is less code and more clearly states the intention of the operation

Comments

1
var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];


var newArr,temp,temp1;


    temp=array1.filter(function(el) 
              {
                return arr2.indexOf(el) == -1; 

              });

    temp1=array2.filter(function(el) 
              {
                return arr1.indexOf(el) == -1; 

              });

  newArr=temp.concat(temp1);


  return newArr;

}

Comments

0

Similar to above but will work with more than two arrays

var array1 = ['12','1','10','19','100'];
var array2 = ['12','10','19'];
var i = 0;
var hist = {};
var array3 = [];

buildhist(array1);
buildhist(array2);

for (i in hist) {
    if (hist[i] === 1) {
        array3.push(i);
    }
}

console.log(array3);

function buildhist(arr) {
    var i;
    for (i = arr.length - 1; i >= 0; i--) {
        if (hist[arr[i]] === undefined) {
            hist[arr[i]] = 0;
        }
        hist[arr[i]]++;
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.