'Compare two Javascript Arrays and remove Duplicates

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>


Solution 1:[1]

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

Solution 2:[2]

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!

Solution 3:[3]

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' ]

Solution 4:[4]

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);
    }
}

Solution 5:[5]

This my solution

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

Solution 6:[6]

You can try this

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

Solution 7:[7]

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.

Solution 8:[8]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Madara's Ghost
Solution 2 Manoz
Solution 3
Solution 4 mix3d
Solution 5 Daniel Ortegón
Solution 6 S_i_l_e_n_t C_o_d_e_r
Solution 7 Sachin Jagtap
Solution 8 External Purpose