How to remove duplicate elements from an array in JavaScript?

JavascriptWeb DevelopmentFront End Technology

There are multiple ways of removing duplicate elements from an array in JavaScript. In this article, we are going to explore some of the top methods to remove duplicate elements.

Using the filter() Method

The filter() method creates a new array of elements with the passed condition. This will only contain the element that returns true as part of this filter method. So to achieve the removal of the duplicate elements we just need to add the condition in the filter() method and it will do the rest of the work.

# filter.js

<script>
   var arr = ["steve", "mark", "mark","bill", "steve", "
   function removeDuplicates(arr) {
      return arr.filter((item,index) => arr.indexOf(item) === index);
   console.log(removeDuplicates(arrr));
</script>

Output

"steve", "mark", "bill"

Using the Set() Method

A Set is a collection of unique values. For removing the elements from an Array we first need to convert an array of duplicates into a Set.

This new Set will implicitly remove the duplicate elements and then convert the back the set to an array.

# filter.js

<script>
   var arr = ["steve", "mark", "mark","bill", "steve", "bill"];

   function removeDuplicates(arr) {
      let uniqueArr = [...new Set(arr)];
      return uniqueArr;
   }
   console.log(removeDuplicates(arr));
</script>

Output

"steve", "mark", "bill"

Using the reduce() Method

The reduce() method is used for reducing the elements of the array and then combining them into a final array based on some reducer function passed by the user. In the below example, we are going to use the reduce() method to delete or remove the duplicate elements from the array.

# filter.js

<script>
   var arr = ["steve", "mark", "mark","bill", "steve", "bill"];

   function removeDuplicates(arr) {
      var unique = arr.reduce(function (acc, curr) {
         if (!acc.includes(curr))
            acc.push(curr);
         return acc;
      }, []);
      return unique;
   }
   console.log(removeDuplicates(arr));
</script>

Output

"steve", "mark", "bill"

Using forEach() and include()

The include() method returns true if an element exists in an array and false if not. In the below example we use forEach() to iterate over the elements of the array and add to the new array only when the same element is not present there.

# filter.js

<script>
   var arr = ["steve", "mark", "mark","bill", "steve", "bill"];

   function removeDuplicates(arr) {
      let uniqueArr = [];
      chars.forEach((c) => {
         if (!uniqueChars.includes(c)) {
            uniqueChars.push(c);
         }
      });
       return uniqueArr;
   }
   console.log(removeDuplicates(arr));
</script>

Output

"steve", "mark", "bill"
raja
Updated on 26-Apr-2022 12:25:42

Advertisements