jquery - Comparing two arrays and getting the non duplicate(not unique) values -
i have 2 sets of arrays. need letters not in both arrays. first should check if index 0 'a' on both arrays. if in both should delete 'a' both(just first 'a' in first array not 1 @ end(index 3). , go the second item 'b' using same logic.
var arraya = ['a','b','c','a'];
var arrayb = ['a','d','f','c'];
var arrayc = []; //shoud have result[b,a,d,f]
the code set @ http://jsfiddle.net/rexonms/abfyh/#base
html
<p class="arraya">array a</p> <p class="arrayb">array b</p> <p class="arrayc">array c</p>
â jquery
var arraya = ['a','b','c','a']; var arrayb = ['a','d','f','c']; var arrayc = []; //shoud have result[b,a,d,f] $('.arraya').text('arraya: ' + arraya); $('.arrayb').text('arrayb: ' + arrayb); $.each(arraya, function(indexa,valuea) { $.each(arrayb, function(indexb, valueb){ if(valuea != valueb) { arrayc.splice(valuea); } }); $('.arrayc').text('arrayc: ' + arrayc); });
here working version of want: http://jsfiddle.net/zzt5f/
var arraya = ['a','b','c','a']; var arrayb = ['a','d','f','c']; var arrayc = []; //should have result[b,a,d,f] $('.arraya').text('arraya: ' + arraya); $('.arrayb').text('arrayb: ' + arrayb); $.each(arraya, function(indexa,valuea) { $.each(arrayb, function(indexb, valueb){ if(valuea == valueb) { arraya[indexa]=null; arrayb[indexb]=null; return false; //break out of inner each loop } }); }); $.each(arraya.concat(arrayb),function(idx,val) { if(val!=null) arrayc.push(val); }); $('.arrayc').text('arrayc: ' + arrayc); alert(arrayc);
as see made few modifications original code. firstly, since trying remove duplicate values, need check if valuea==valueb
, not vice-versa. once match has been found, second iteration needs halt prevent removal of second duplicate in second array, hence return false
.
i didn't use array.splice method, because creates , returns new array removing values array called on, wasn't doing way using it. felt cleaner not keep creating new arrays within loop. note method modify arraya
, arrayb
, if need them again later on have clone them.
â
Comments
Post a Comment