Home >Web Front-end >JS Tutorial >Duplicate Value remove

Duplicate Value remove

Patricia Arquette
Patricia ArquetteOriginal
2025-01-05 12:17:40992browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn