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>
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With