89

It is working well is there any other better way to remove duplicates from one array if it has elements of another array ?.

<script>
var array1 = new Array("a","b","c","d","e","f");
var array2 = new Array("c","e");

for (var i = 0; i<array2.length; i++) {
    var arrlen = array1.length;
    for (var j = 0; j<arrlen; j++) {
        if (array2[i] == array1[j]) {
            array1 = array1.slice(0, j).concat(array1.slice(j+1, arrlen));
        }
    }
}
alert(array1);

</script>
1
  • I could be wrong but I don't think this would be perform-ant. You're doing 2 loops Commented May 5, 2015 at 19:17

8 Answers 8

226
array1 = array1.filter(function(val) {
  return array2.indexOf(val) == -1;
});

Or, with the availability of ES6:

array1 = array1.filter(val => !array2.includes(val));

filter() reference here

indexOf() reference here

includes() reference here

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

6 Comments

As a side note and explanation of the above code : "indexOf : Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found." (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)
I like it, but it definitely needs explanation, or at least a link guiding someone to the right place that explains it.
Great piece of code, though be aware that it doesn't work if you have nested arrays.
Works beautiful for lists of unique values, but what about lists with duplicates in them, such as comparing a "ransom note" with a list of words in a magazine (assuming case must match and must have the right number of each word)...
It worked for me . (array1 = array1.filter(val => !array2.includes(val));). Thank you. :)
|
10

The trick, for reasons that are beyond me, is to loop the outer loop downwards (i--) and the inner loop upwards (j++).

See the example bellow:

function test() {
  var array1 = new Array("a","b","c","d","e","f");
  var array2 = new Array("c","e");
  for (var i = array1.length - 1; i >= 0; i--) {
    for (var j = 0; j < array2.length; j++) {
      if (array1[i] === array2[j]) {
        array1.splice(i, 1);
        }
      }
    }
    console.log(array1)
  }

How do I know this? See the below:

for( var i =myArray.length - 1; i>=0; i--){
  for( var j=0; j<toRemove.length; j++){
    if(myArray[i] === toRemove[j]){
      myArray.splice(i, 1);
    }
  }
}

or

var myArray = [
  {name: 'deepak', place: 'bangalore'}, 
  {name: 'chirag', place: 'bangalore'}, 
  {name: 'alok', place: 'berhampur'}, 
  {name: 'chandan', place: 'mumbai'}
];
var toRemove = [
  {name: 'deepak', place: 'bangalore'},
  {name: 'alok', place: 'berhampur'}
];

for( var i=myArray.length - 1; i>=0; i--){
    for( var j=0; j<toRemove.length; j++){
        if(myArray[i] && (myArray[i].name === toRemove[j].name)){
            myArray.splice(i, 1);
        }
    }
}

alert(JSON.stringify(myArray));

On that note, would anyone be able to explain why the outer loop needs to be looped downwards (--)?

Good luck!

2 Comments

How can remove the duplicate without using property name.like without specify any array obj name .
@vishal change array1[i] === array2[j] to extend the propery name of the item. That makes it now array1[i].propertyOfThisItem === array2[j].possiblyTheSameProperty
9

You can try this

array1 = array1 .filter(val => {
             return !array2.find((val2)=>{
              //  console.log({valueID:val.id+":"+val2.id});
                return val.id===val2.id
             }) 
            });

Comments

6

Using the Set.prototype Constructor: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

let array1 = Array('a', 'b', 'c', 'd', 'e', 'f')
let array2 = Array('c', 'e', 'g')
let concat = array1.concat(array2) // join arrays => [ 'a', 'b', 'c', 'd', 'e', 'f', 'c', 'e', 'g' ]

// Set will filter out duplicates automatically
let set = new Set(concat) // => Set { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }

// Use spread operator to extend Set to an Array
let result = [...set]
console.log(result) // =>  [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]

1 Comment

@Drenai yes it works for objects if you stringify :)
2

use Array.splice()

var array1 = ['1', '2', '3', '4', '5'];
var array2 = ['4', '5'];
var index;
for (var i=0; i<array2.length; i++) {
    index = array1.indexOf(array2[i]);
    if (index > -1) {
        array1.splice(index, 1);
    }
}

Comments

2

This is my solution to remove duplicate in ES6.

let foundDuplicate = false;
existingOptions.some(existingItem => {
  result = result.filter(item => {
    if (existingItem.value !== item.value) {
      return item;
    } else {
      foundDuplicate = true;
    }
  });
  return foundDuplicate;
});

I used this approach because in my case I was having array of objects and indexOf was having problem with it.

Comments

1

This my solution

array1 = array1.filter(function(val) { return array2.indexOf(val.toString()) == -1; });

1 Comment

Was the top answer not sufficient? Why is the additional .toString() necessary?
0
window.onload = function () {
        var array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];
        var array2 = ['c', 'h', 'k'];
        var array3 = [];
        var SecondarrayIndexcount = 0;
        for (var i = 0; i < array1.length; i++) {
            for (var j = 0; j < array2.length; j++) {
                if (array1[i] !== array2[j]) {
                    if (SecondarrayIndexcount === (array2.length - 1)) {
                        array3.push(array1[i]);
                        SecondarrayIndexcount = 0;
                        break;
                    }
                    SecondarrayIndexcount++;
                }
            }
        }
        for (var i in array3) {
            alert(array3[i]);
        }
    }
</script>

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.