How to remove duplicate values from a JavaScript Array?
Answer: Using indexOf()
method
In this lesson, we are going to learn how to remove duplicate values from a JavaScript array. JavaScript has several methods, by which we can remove the duplicate elements from the array. Some of the methods are given below:
-
indexOf() method
-
filter() method
Using indexOf()
method
JavaScript offers the indexOf()
method, by which we can find the index of element and then remove the duplicate values from the given array.
The indexOf()
method searches for the specific element within the array and returns its value. This method returns the index of the first occurrence of an element within the array.
This method searches for the specified value and returns its position. If the value is present more than once, then this method returns the position of the first occurrence and returns -1 if the value is not present. When we get the position of the specified value then we pass that position to push method to remove that particular value from the array.
Example: Using indexOf()
method
In this example, we have used the indexOf()
method to remove the duplicate values from the given array.
<!DOCTYPE html>
<html>
<head>
<title>Remove duplicate array values in JavaScript</title>
</head>
<body>
<script>
function getUnique(array){
var uniqueArray = [];
for(i=0; i < array.length; i++){
if(uniqueArray.indexOf(array[i]) === -1) {
uniqueArray.push(array[i]);
}
}
return uniqueArray;
}
var fruits = ["Apple", "Mango", "Banana", "Pears", "Banana", "Pears"];
var newArr = getUnique(fruits);
console.log(newArr);
</script>
</body>
</html>
Output
["Apple", "Mango", "Banana", "Pears"]
Using filter()
Function
We can also remove the duplicate values from an array using the filter()
method. The filter()
method creates a new array with all the elements that pass the test implemented by the provided function. Any array element that fails the test or returns false then that element will not be included in the filtered array.
Example: Using filter()
function
In the given example, we have used the filter()
method along with the indexOf method to filter the duplicate values from the given array.
<!DOCTYPE html>
<html>
<head>
<title>Remove duplicate array values in JavaScript</title>
</head>
<body>
<script>
var arr = ["Apple", "Mango", "Banana", "Apple", "Pears", "Watermelon"];
function dupArr(data){
return data.filter((value, index) => data.indexOf(value) === index);
}
console.log(dupArr(arr));
</script>
</body>
</html>
Output
["Apple", "Mango", "Banana", "Pears", "Watermelon"]
Conclusion
In this lesson, we have learned how to remove duplicate values from the given array. Here, we have discussed two methods to remove the duplicate values from the given array. In the first method, we have used the indexOf()
method that enables us to remove the duplicate values from the given array. In the second method, we have used the filter()
method. It filters the array elements.