Home >Web Front-end >JS Tutorial >Duplicate Value remove
Removing Duplicates from Arrays
Method 1: Using Set
The Set object in JavaScript automatically removes duplicate values. This makes it a straightforward solution.
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Method 2: Using filter()
The filter method can be combined with indexOf to only keep the first occurrence of each element.
const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]
Method 3: Using reduce()
Using reduce, you can build a new array that only includes unique elements.
The above is the detailed content of Duplicate Value remove. For more information, please follow other related articles on the PHP Chinese website!