Compare two Javascript Arrays and remove Duplicates

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!


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

Tags:

Javascript