JavaScript: How to filter out Non-Unique Values from an Array?

JavascriptWeb DevelopmentFront End Technology

Arrays are data structures used to store data in a structured format. We can store the data in an array and retrieve them using their indexes. These indexes serve as a key for these values.

In this article, we will filter out non-unique values and return an array that only contains unique non-repeating elements.

Approach

In an array of unique elements, we will fetch all the elements and then compare them with the set of previous elements. If any of the elements exists already, it means it’s a duplicate element and we will remove it from the resultant array.

In this article, we will be using the filter() method and the forEach() method for filtering out the non-unique values.

Approach 1 − Using filter() Method

The filter() method returns the elements that satisfy the one occurrence conditions. We will use the indexOf() feature provided by JavaScript to remove all the repeating elements.

Syntax

var newArr=initialArr.filter((value ,index)=>{
   // conditions with return
});

Example 1

In the below example, we are going to remove all the repeating numbers

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Filtering the Non-unique characters</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      var array=[1, 1, 2, 3, 3, 5, 6, 7, 7, 7, 8, 9];
      console.log("Before filtering non unique values: " + array);
      var unique=array.filter((value, index) => {
         return array.indexOf(value) === array.lastIndexOf(value);
      });
      console.log("After filtering non unique values: " + unique);
   </script>
</body>
</html>

Output

On successful execution of the above program, the browser will display the following result.

Welcome To Tutorials Point

And in the console, you will find the results, see the screenshot below −

Approach 2 − Using for() Loop

Using the for() loop will only push the unique elements into the array. We will use the indexOf() method to check if the first and the last occurrence of the element are the same.

Example 2

In the below example, we are going to remove all the repeating numbers

# index.html

<!DOCTYPE html>
<html>
<head>
   <title>Filtering the Non-unique characters</title>
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <script>
      var array = [1, 1, 2, 3, 3, 5, 6, 7, 7, 7, 8, 9];
      console.log("Before filtering: " + array);
      var unique = [];
      for (let i = 0; i < array.length; i++) {
         if (array.lastIndexOf(array[i]) === array.indexOf(array[i])) {
            unique.push(array[i]);
         }
      }
      console.log("After filtering: " + unique);
   </script>
</body>
</html>

Output

raja
Updated on 26-Apr-2022 08:43:43

Advertisements