0

I have a array a=[1,2,3,4,5] b=[3,4,5,6,7]

Here i want values of array a [1,2] and array b [6,7] and stored in diff arrays like below.

c=[1,2] d=[6,7]

Thanks in Advance.

its like a=[chkbx_705_49,chkbx_706_49,chkbx_707_49,chkbx_708_49,chkbx_709_49,chkbx_710_49,chkbx_711_49,chkbx_712_49,chkbx_714_49,chkbx_705_50,chkbx_706_50,chkbx_707_50,chkbx_708_50,chkbx_709_50,chkbx_710_50,chkbx_711_50,chkbx_705_51,chkbx_706_51,chkbx_707_51,chkbx_708_51,chkbx_711_51,chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53]

b= [chkbx_705_49,chkbx_705_50,chkbx_705_51,chkbx_705_52,chkbx_705_53,chkbx_706_49,chkbx_706_50,chkbx_706_51,chkbx_706_52,chkbx_706_53,chkbx_707_49,chkbx_707_50,chkbx_707_51,chkbx_708_49,chkbx_708_50,chkbx_708_51,chkbx_709_49,chkbx_709_50,chkbx_710_49,chkbx_710_50,chkbx_711_49,chkbx_711_50,chkbx_711_51,chkbx_712_49]

here i deleted chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53 checkbox values from array a

and added chkbx_705_52,chkbx_705_53,,chkbx_706_52,chkbx_706_53 added in array b.

So i want c = chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53

d = chkbx_705_52,chkbx_705_53,,chkbx_706_52,chkbx_706_53

kiranstack
  • 1
  • 1
  • 2
  • The pre-built set objects described in [this post](http://stackoverflow.com/questions/7958292/mimicking-sets-in-javascript/7958422#7958422) and [here on GitHub](https://github.com/jfriend00/Javascript-Set/blob/master/set.js) have all sorts of methods for analyzing sets of objects such as your arrays: `.difference()`, `.union()`, `.intersection()`, `.isSubset()`, `.isSuperSet()`, etc... You can either use them or look at how the code works. – jfriend00 Dec 04 '14 at 05:41

2 Answers2

2

When a member of A also exists in B, delete in both:

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

var c = a.slice();
var d = b.slice();
var len = c.length;

while(len--) {
  var idx = d.indexOf(c[len]);
  if (idx > -1) {
    c.splice(len, 1);
    d.splice(idx, 1);
  }
}

However, you didn't say whether there are duplicated members, so I assume no and do it in the simplest way, just to give you a thought of solution.

Leo
  • 13,428
  • 5
  • 43
  • 61
  • there are duplicates in both arrays (3,4,5) and i jus want to retrive only c=[1,2] d=[6,7] values – kiranstack Dec 04 '14 at 07:38
  • No, I mean I assume you don't have duplicates in a single array, say `a = [1,2,3,3,4,5]`. However, remove duplicates within an array is another question, so I skip it. – Leo Dec 04 '14 at 08:03
  • Try my code, it works for your example. – Leo Dec 04 '14 at 08:04
1

You can get it like below:

var array1 = [1,2,3,4,5];
var array2 = [3,4,5,6,7];
var foo1 = [], foo2=[];
var i = 0;
jQuery.grep(array1, function(el) {

    if (jQuery.inArray(el, array2) == -1) foo1.push(el);
    i++;

});
jQuery.grep(array2, function(el) {
    if (jQuery.inArray(el, array1) == -1) foo2.push(el);
     i++;
});
alert(" the difference is " + foo1);
alert(" the difference is " + foo2);
user3263194
  • 453
  • 6
  • 20