6

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?

user113716
  • 318,772
  • 63
  • 451
  • 440
sken boy
  • 137
  • 2
  • 11
  • 3
    http://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript – Gerry Sep 13 '11 at 14:58
  • thx for the response but this question is about returning an array with intersected elements . i want to delete them and return the rest in a new array – sken boy Sep 13 '11 at 15:02

4 Answers4

9

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)
Robert
  • 39,162
  • 17
  • 99
  • 152
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • 2
    +1 [Working example.](http://jsbin.com/ayujef/edit#javascript,live) Probably safe to assume that underscore code is acceptable since jQuery is apparently already loaded. – user113716 Sep 13 '11 at 15:27
  • Thanks for the working example - looks great :) .. Underscore is similar to jQuery in philosophy and the size isn't too big either, but it all depends on OP's requirements. – Anurag Sep 13 '11 at 15:51
5

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

Joe
  • 80,724
  • 18
  • 127
  • 145
  • thanks abstractdownvotefactor, the arrays are stocked in a var and dont know ther indexes neither the elements . – sken boy Sep 13 '11 at 15:07
  • This won't give you elements in `array2` that don't appear in `array1`. OP's example seems to suggest that all unique values are retained. – user113716 Sep 13 '11 at 15:16
  • This will have a different result if you started filtering out from `array2`. The contents are both the arrays are unknown. – Anurag Sep 13 '11 at 15:16
  • Good improvement and an interesting solution, but just one nitpick is that you're not retaining the result (since `.filter()` returns a new Array). Perhaps just chain the `.filter()` off the `.concat()`. `var a = array1.concat(array2).filter(function (...` *EDIT:* +1 though. – user113716 Sep 13 '11 at 15:40
2

Well, since you specified jQuery, try this:

var arr1 = [2, 3, 4];
var arr2 = [1, 2, 3];

var arr3 = $.merge($.grep(arr1, function(el, idx) {
    return $.inArray(el, arr2) > -1;
}, true), $.grep(arr2, function(el, idx) {
    return $.inArray(el, arr1) > -1;
}, true));

alert(arr3);

It's probably not very efficient, but it's relatively concise.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • thankx for the response but how can i implement this and return an array without the intersected elements ??? – sken boy Sep 13 '11 at 15:03
0

Plain js solution, not as efficient as when jQuery is used:

function filter(a1, a2){
  var result = [];
  for(i in a1){
    exists = false;
    for(j in a2){
      if(a1[i] == a2[j])
        exists = true;
    }
    if(exists== false){
      result.push(a1[i]);
    }
  }
  return result;
}

var arr1 = [1,2,3,4,5];
var arr2 = [4,5,6,7,8];
var result1 = filter(arr1, arr2);
var result2 = filter(arr2, arr1);

var result = result1.concat(result2);
Kir Chou
  • 2,980
  • 1
  • 36
  • 48
mooglife
  • 226
  • 1
  • 2
  • 8
  • You really shouldn't use `for-in` on an Array *(in JavaScript)*. – user113716 Sep 13 '11 at 15:45
  • i finally used underscore plugin and the code of @anurag. thank you for the help – sken boy Sep 13 '11 at 15:46
  • @patrick dw: agreed that for-in shouldn't be used in javascript where order of parsing the elements are important. Thats the only drawback of it, me thinks. – mooglife Sep 13 '11 at 17:37
  • Well, it also forces you to use `.hasOwnProperty()` if you use any code that extends `Array.prototype` (which can be very useful). For Array iteration, an index-based `for` statement will be better than the more general `for-in` enumerator. – user113716 Sep 13 '11 at 17:43