How to useindexOf() Method in Javascript
The indexOf() method is used to find the first index of occurrence of an array element. we can iterate over the elements in the array, and we will push into the new array if it doesn’t exist in the resultant array.
Example: In this example, we will see the use of the indexOf() method.
let arr = ["apple", "mango",
"apple", "orange", "mango", "mango"];
function removeDuplicates(arr) {
let unique = [];
for (i = 0; i < arr.length; i++) {
if (unique.indexOf(arr[i]) === -1) {
unique.push(arr[i]);
}
}
return unique;
}
console.log(removeDuplicates(arr));
Output
[ 'apple', 'mango', 'orange' ]
How to get all unique values (remove duplicates) in a JavaScript array?
We are going to learn How to get all unique values (remove duplicates) in a JavaScript array. Given an array with various values, our objective is to filter out any duplicates and display the resulting array in the console.
We can get all unique values in a JavaScript array in the following ways:
Table of Content
- Method 1: Using for loop
- Method 2: Using the Array filter() method:
- Method 3: Using set() Method
- Method 4: Using reduce() Method
- Method 5: Using forEach() Method
- Method 6: Using indexOf() Method
- Method 7: Using Underscore.js _.uniq() Function