Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the unique values from two arrays and put them in another array [duplicate]

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.

like image 634
sanchitkhanna26 Avatar asked Apr 09 '13 21:04

sanchitkhanna26


People also ask

How do I combine two arrays?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.


2 Answers

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.

like image 192
Bart Avatar answered Sep 30 '22 16:09

Bart


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] 
like image 29
Hedley Smith Avatar answered Sep 30 '22 17:09

Hedley Smith