Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given two Arrays, return an Array consisting only of the non-intersecting items

I'm getting stacked in an issue in JavaScript.

I have two arrays and I want to check if they intersect on some elements then delete those elements and return new array without the intersected elements.

example :

Array A ( 
[0] => 0 [1] => 1 
)

Array B ( 
[0] => 2 [1] => 1 
)

I want to check them and return:

 Array result ( 
[0] => 0 [1] => 2 
)

How can i do this in JavaScript?

like image 311
sken boy Avatar asked Sep 13 '11 14:09

sken boy


2 Answers

Checkout the library underscore.js.

Say you have two arrays,

var a = [1, 2];
var b = [2, 3];

First find the union.

var all = _.union(a, b);

Then find the intersection.

var common = _.intersection(a, b);

The final answer should be the difference between the union, and the intersection.

var answer = _.difference(all, common)
like image 57
Anurag Avatar answered Nov 15 '22 07:11

Anurag


Using Array.filter, Array.lastIndexOf, and Array.indexOf:

var array1 = [1,2,3,4,5];
var array2 = [2,3];
var unique = array1.concat(array2)
                   .filter(function (item, index, array) {
                       return array.indexOf(item) == array.lastIndexOf(item);
                   })

Neither method is 100% cross browser by default, but both links having safe shims for IE <= 8

like image 35
Joe Avatar answered Nov 15 '22 06:11

Joe