-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?

2

2 Answers 2

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;
});
Sign up to request clarification or add additional context in comments.

6 Comments

Property or Method indexOf is undefined...
Works fine for me on Firefox 23.0.1. What does your browser say if you do this? alert(Array.prototype.indexOf); ? If it alerts a function, my code should work. If not... that's really weird because filter and indexOf were added in the same version of JavaScript.
The indexOf() method is not supported in Internet Explorer 8 and earlier.
try this if the browser is <IE 9. if(!Array.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]==obj){ return i; } } return -1; } }
Ah... then why is .filter() supported? Weird. I updated my answer for the asker, for IE8 and earlier.
|
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/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.