Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two Javascript Arrays and remove Duplicates

Tags:

javascript

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> 
like image 901
sunleo Avatar asked Feb 18 '13 06:02

sunleo


People also ask

How we can compare two arrays in JavaScript?

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.

How can you eliminate duplicate values from a JavaScript array?

Answer: Use the indexOf() Method You can use the indexOf() method in conjugation with the push() remove the duplicate values from an array or get all unique values from an array in JavaScript.


1 Answers

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

like image 169
Aesthete Avatar answered Sep 19 '22 08:09

Aesthete