Skip to content

Remove duplicate values from array JavaScript | Simple examples

  • by

You can use multiple ways to Remove duplicate values from an array in JavaScript. The easiest way is using the set or native filter method of an Array.

Examples of Remove duplicate values from array JavaScript

Let’s see multiple examples.

Using a Set

A Set is a collection of unique values. First, convert an array of duplicates to a Set. The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.

<!DOCTYPE html>
<html>
<head>

    <script>
        let chars = ['A', 'B', 'A', 'C', 'B'];
        let uniqueChars = [...new Set(chars)];

        alert(uniqueChars);
    </script>
</head>
<body>

</body>
</html>

Output:

Remove duplicate values from array JavaScript

Native filter method of an Array

Here is HTML example code to get an array with unique values in JS.

To remove the duplicates, you use the filter() method to include only elements whose indexes match their indexOf values:

<!DOCTYPE html>
<html>
<head>

    <script>

        function onlyUnique(value, index, self) {
          return self.indexOf(value) === index;
      }

      var a = ['A', 'B', 'A', 'C', 'B'];
      var unique = a.filter(onlyUnique);

      alert(unique);
  </script>
</head>
<body>

</body>
</html>

Do you have any doubts, suggestions, or examples? Do comment below.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading