Skip to content
Related Articles

Related Articles

Improve Article

How to filter out the non-unique values in an array using JavaScript ?

  • Difficulty Level : Medium
  • Last Updated : 21 May, 2021

In JavaScript, arrays are the object using the index as the key of values. In this article, let us see how we can filter out all the non-unique values and in return get all the unique and non-repeating elements.

Approach: In the array for unique elements, the index of the first and last occurrence of the elements must be the same, otherwise, if they are different, it confirms that the array has the duplicate at some other index in the same array. All the non-unique values should be stopped by the filter() and the output should be unique values.

Method 1: Using filter() method

The filter() method returns the array elements that satisfy the condition that the first occurrence index and last occurrence index must be the same for a unique element. We use the indexOf() method to get the index first occurrence of an element and the lastIndexOf() method to get the last occurrence of an element.

Syntax:



var newarr=initial_arr.filter((value ,index)=>{
  conditions with return statement;
});

Example:

Javascript




<script>
  var array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8];
  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>

Output:

Before filtering non unique values: 1,2,2,3,4,5,6,6,7,8,8,8
After filtering non unique values: 1,3,4,5,7

Method 2: Using the same principle but using a for() loop.

In the for loop, we only push our unique elements into the array, if it satisfies the condition that the first occurrence index and last occurrence index must be the same. We use the indexOf() method to get the index first occurrence of an element and the lastIndexOf() method to get the last occurrence of an element.

Syntax:

for (let i = start; condition to i;increment or decrement) {
    instruction1;
    instruction2;
    instruction3;
    .
    .
    .
};

Example:

Javascript




<script>
  var array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8];
  console.log("Before filtering non unique values: " + 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 non unique values: " + unique);
</script>


Output:
Before filtering non unique values: 1,2,2,3,4,5,6,6,7,8,8,8
After filtering non unique values: 1,3,4,5,7




My Personal Notes arrow_drop_up
Recommended Articles
Page :