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]
5
  • You need to explain this a lot better, you're probably looking for concat(), but who knows ? Commented Dec 31, 2013 at 11:36
  • see if this helps you out Commented Dec 31, 2013 at 11:37
  • val() doesn't even return arrays ? Commented Dec 31, 2013 at 11:37
  • @adeneo for SELECT with attribute multiple, jquery val() returns array. I was thinking the same... Commented Dec 31, 2013 at 11:39
  • @A.Wolff - It would, but plain javascript wouldn't, one of those convenient things added by jQuery. Commented Dec 31, 2013 at 11:43

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

2 Comments

TypeError: a.filter is not a function.filter(function(a){return this.indexOf(a) === -1},[1,2,5]); //=> [4]
@monda: in that case you probably need the shim/Polyfill from the 'See also' link. Idem for indexOf, see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
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

Comments

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

Comments

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.