Skip to content
Related Articles

Related Articles

How to Remove duplicate elements from array in JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 28 Jul, 2022

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

Time complexity: O(n2) as there is nested list involved.

Auxiliary Space: O(n) 

Using Array.filter() method: We use the JavaScript indexOf() method which returns smallest index  of number if duplicate element is present in Array and check the current element index with 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' ]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!