How to Remove duplicate elements from array in JavaScript ?
There are various different methods for finding the duplicates in the array. We will discuss two ways for finding the duplicates in the array.
JavaScript Set: The Set object lets you store unique values of any type, whether primitive values or object references. This is the easiest method to remove the duplicate element and get unique elements from an array.
Example: Suppose we have an array called City which consists of duplicate city names and we want to remove the duplicates and find the unique elements from it.
Javascript
<script> // Defining a set of the cities let city = [ "surat" , "ahmedabad" , "rajkot" , "mumbai" , "surat" , "delhi" , "ahmedabad" , "anand" , ]; // For removing the duplicate values // we are using the Set() function let unique_city = [ new Set(city)]; // Printing the unique cities console.log(unique_city); </script> |
Output:
["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]
JavaScript forEach() Method: We use the JavaScript includes() function which returns true if an element is in an array or false if it is not present.
Example: The following example iterates over elements of an array and adds elements to a new array that are not already present.
Javascript
<script> // Defining a set of the cities let city = [ "surat" , "ahmedabad" , "rajkot" , "mumbai" , "surat" , "delhi" , "ahmedabad" , "anand" , ]; // Defining the unique cities from the above // array by using forEach loop let unique_city = []; city.forEach((c) => { if (!unique_city.includes(c)) { unique_city.push(c); } }); // Printing the unique cities console.log(unique_city); </script> |
Output:
["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]
JavaScript Array.filter() method: We use the JavaScript indexOf() method which returns the smallest index of the number if a duplicate element is present in the Array and check the current element index with the return value. On the basis of check, we filter the Array.
Javascript
<script> // Defining a set of the cities let city = [ "surat" , "ahmedabad" , "rajkot" , "mumbai" , "surat" , "delhi" , "ahmedabad" , "anand" , ]; // Defining the unique cities from the above // array by using filter let unique_city = city.filter((c, i) =>city.indexOf(c) === i ); // Printing the unique cities console.log(unique_city); </script> |
Output:
[ 'surat', 'ahmedabad', 'rajkot', 'mumbai', 'delhi', 'anand' ]
Please Login to comment...