How to use the filter() method In Javascript
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.
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);
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
How to filter out the non-unique values in an array using JavaScript ?
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:
Table of Content
- Using the filter() method
- Using for loop
- Using Set and filter
- Using the reduce() Method