Skip to content
Related Articles

Related Articles

Improve Article

How to Remove duplicate elements from array in JavaScript ?

  • Last Updated : 06 Aug, 2021
Geek Week

There are various different methods for finding the duplicates in the array. We will discuss two ways for finding the duplicates in the array.

Using 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 the 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"]

 



Using 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.

The following example iterates over elements of an array and adds elements to a new array that are not already present.

Example :

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

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it’s lowest price ever!




My Personal Notes arrow_drop_up
Recommended Articles
Page :