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.
These are the following ways by which we can filter out the non-unique values in an array:
Method 1: Using the filter() method
The filter() method returns the array of 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:
let newarr=initial_arr.filter((value ,index)=>{
conditions with return statement;
});
Example: In this example, we will use the filter() and indexOf() methods to filter out the non-unique values in an array using JavaScript.
Javascript
let array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8]; console.log( "Before filtering non unique values: " + array); let unique = array.filter((value, index) => { return array.indexOf(value) === array.lastIndexOf(value); }); console.log( "After filtering non unique values: " + unique); |
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 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: In this example, we will use for loop to filter out the non-unique values in an array using JavaScript.
Javascript
const array = [1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 8, 8]; console.log( "Before filtering non unique values: " + array); let 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); |
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