Compare two Javascript Arrays and remove Duplicates

Javascript

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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

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

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

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

This my solution

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

Solution 6 - Javascript

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

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

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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsunleoView Question on Stackoverflow
Solution 1 - JavascriptAestheteView Answer on Stackoverflow
Solution 2 - JavascriptBenisburgersView Answer on Stackoverflow
Solution 3 - JavascriptFlavioView Answer on Stackoverflow
Solution 4 - JavascriptJijo PauloseView Answer on Stackoverflow
Solution 5 - JavascriptDaniel OrtegónView Answer on Stackoverflow
Solution 6 - JavascriptS_i_l_e_n_t C_o_d_e_rView Answer on Stackoverflow
Solution 7 - JavascriptSachin JagtapView Answer on Stackoverflow
Solution 8 - JavascriptExternal PurposeView Answer on Stackoverflow