-2
var arr1=["a","b","b","c","c","d"];
var arr2=["b","c",];

arr1 has duplicate values which are listed in arr2. Now I want to remove the duplicate values from arr1 using arr2. Is it possible?

Pearl
  • 8,373
  • 8
  • 40
  • 59
  • http://stackoverflow.com/questions/13486479/javascript-array-unique – Asif Sep 26 '13 at 06:00
  • Visit this link http://stackoverflow.com/questions/14930516/compare-two-javascript-arrays-and-remove-duplicates –  Sep 26 '13 at 06:06

2 Answers2

1

I would use the Array's .filter() method.

arr1 = arr1.filter(function (val) {
    return arr2.indexOf(val) === -1;
});




For IE8 or earlier, this code should work:

arr1 = arr1.filter(function (val) {
    var i;
    for (i = 0; i < arr2.length; i += 1) {
        if ( val === arr2[i] ) {
            return false;
        }
    }
    return true;
});
Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
1

you can use directly to remove duplicates from array1 as

 $(document).ready(function(){
     var arr1=["a","b","b","c","c","d"];
     var arr2=[];   

     $.each(arr1, function(i,el){
            if($.inArray(el, arr2) === -1) 
                arr2.push(el);
           });
      alert(arr2);
   });

you can observe here..

http://jsfiddle.net/nPeaV/7410/