0

I have two arrays

 var a= $("#update-select1").val();  // gives value 1,2,4
 var b= $("#update-select2").val();  // 1,2,5

I want two different arrays from the above two arrays.

//array has the values which is in  `b` but not in `a`
var c = [5]

//another array has value in `a` but not in `b`
var d =[4]
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
monda
  • 3,809
  • 15
  • 60
  • 84

4 Answers4

2

You can use Array.filter this way:

var c = [1,2,5]
          .filter(function(a){return this.indexOf(a) === -1},[1,2,4]); //=> [5]
var d = [1,2,4]
          .filter(function(a){return this.indexOf(a) === -1},[1,2,5]); //=> [4]

Or:

function notIn(a){
   return this.indexOf(a) === -1;
}
var a = [1,2,4]
   ,b = [1,2,5]
   ,c = b.filter(notIn,a)
   ,d = a.filter(notIn,b);

See also

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • TypeError: a.filter is not a function.filter(function(a){return this.indexOf(a) === -1},[1,2,5]); //=> [4] – monda Dec 31 '13 at 12:06
  • @monda: in that case you probably need the shim/Polyfill from the 'See also' link. Idem for `indexOf`, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf – KooiInc Dec 31 '13 at 12:07
1

You can try the grep() method

var a1 = [1, 2, 4];
var a2 = [1, 2, 5];
var difference = $.grep(a1, function (x) {
                     return $.inArray(x, a2) < 0
                 });

alert(" the difference is " + difference);​  

JSFiddle

chridam
  • 100,957
  • 23
  • 236
  • 235
1

I know this is an old question, but I thought I would share this little trick.

var diff = $(old_array).not(new_array).get();

diff now contains what was in old_array that is not in new_array

Found this on Compare 2 arrays which returns difference

Community
  • 1
  • 1
Nitin Varpe
  • 10,450
  • 6
  • 36
  • 60
0

try something like this

var a= [1,2,4];
var b= [1,2,5];

 var c = [];
 jQuery.each(b,function(k,v){
    if(a.indexOf(v) < 0){
        c.push(v);
    }
 })
 console.log(c);//[5]

 var d = [];
 jQuery.each(a,function(k,v){
    if(b.indexOf(v) < 0){
        d.push(v);
    }
 })
 console.log(d);//[4]
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40