To remove duplicate values from an array, you can use various approaches. Here are a couple of common methods:
Using the
filter()
method and theindexOf()
method:
s
function removeDuplicates(arr) {
return arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
});
}
var array = [1, 2, 3, 4, 3, 2, 5, 6, 1];
var uniqueArray = removeDuplicates(array);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]
s
In this example, the
removeDuplicates
function uses thefilter()
method to create a new array that includes only the elements for which the callback function returnstrue
. The callback function checks if the index of the current elementvalue
in the original array is equal to the first occurrence of that element in the array. If they are equal, it means the element is unique, and it is included in the new array.Using the
Set
data structure:
s
function removeDuplicates(arr) {
return Array.from(new Set(arr));
}
var array = [1, 2, 3, 4, 3, 2, 5, 6, 1];
var uniqueArray = removeDuplicates(array);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]
s
In this example, the
removeDuplicates
function creates aSet
using the input array. TheSet
automatically removes duplicate values since it only allows unique values. Then,Array.from()
is used to convert theSet
back into an array, resulting in an array with only unique values.
Both methods provide the same result, which is a new array containing only the unique values from the original array.
No comments:
Post a Comment