Home > Article > Web Front-end > How to remove duplicate elements from JavaScript array?
In JavaScript, there are several ways to remove duplicate elements from an array. In this article, we will explore some of the top methods for removing duplicate elements.
filter()The method creates a new array of elements using the passed conditions. This will only include elements that return true as part of this filter method. So, to remove duplicate elements, we just need to add a condition in the filter() method and it will do the rest.
#Filter.js
<script> var arr = ["steve", "mark", "mark","bill", "steve", " function removeDuplicates(arr) { return arr.filter((item,index) => arr.indexOf(item) === index); console.log(removeDuplicates(arrr)); </script>
"steve", "mark", "bill"
Set is a collection of unique values. In order to remove elements from an array, we first need to convert the duplicate array into a Set.
This new Set will implicitly remove duplicate elements and then convert it back into a set into an array.
#filter.js
<script> var arr = ["steve", "mark", "mark","bill", "steve", "bill"]; function removeDuplicates(arr) { let uniqueArr = [...new Set(arr)]; return uniqueArr; } console.log(removeDuplicates(arr)); </script>
"steve", "mark", "bill"
reduce# The ##() method is used to reduce the elements of an array and then combine them into a final array based on some reducer function passed by the user. In the following example, we will delete or remove duplicate elements from an array using reduce() method.
# filter.js
<script> var arr = ["steve", "mark", "mark","bill", "steve", "bill"]; function removeDuplicates(arr) { var unique = arr.reduce(function (acc, curr) { if (!acc.includes(curr)) acc.push(curr); return acc; }, []); return unique; } console.log(removeDuplicates(arr)); </script>Output
"steve", "mark", "bill"
include() method will return true, otherwise it will return false. In the following example, we use forEach() to iterate over the elements of an array and add it to a new array only if the same element does not exist there.
#filter.js
<script> var arr = ["steve", "mark", "mark","bill", "steve", "bill"]; function removeDuplicates(arr) { let uniqueArr = []; chars.forEach((c) => { if (!uniqueChars.includes(c)) { uniqueChars.push(c); } }); return uniqueArr; } console.log(removeDuplicates(arr)); </script>Output
"steve", "mark", "bill"
The above is the detailed content of How to remove duplicate elements from JavaScript array?. For more information, please follow other related articles on the PHP Chinese website!