For two arrays, we return an array consisting of only disjoint elements

I am having a problem with JavaScript.

I have two arrays and I want to check if they intersect on some elements and then delete these elements and return a new array without intersecting 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?

+5
source share
4 answers

Check out the underscore.js library .

Say you have two arrays,

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

First find the pool.

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

Then we find the intersection.

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

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

var answer = _.difference(all, common)
+8
source

Array.filter, Array.lastIndexOf, 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);
                   })

100% - , IE <= 8

+4

Well, since you specified jQuery, try the following:

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 is probably not very effective, but it is relatively short.

+2
source

Plain js solution is not as efficient as when using jQuery:

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);
Run code
0
source

All Articles