Home > Web Front-end > JS Tutorial > How to Find Unique Values in a JavaScript Array Using `Set`?

How to Find Unique Values in a JavaScript Array Using `Set`?

Susan Sarandon
Release: 2024-11-10 07:58:03
Original
1021 people have browsed it

How to Find Unique Values in a JavaScript Array Using `Set`?

Getting Unique Values in an Array Using JavaScript

To extract unique values from an array, the need for a second array is not always necessary. JavaScript does not possess a hashmap structure similar to Java. However, ES6 introduces the Set object, which can be utilized to achieve uniqueness.

A highly concise solution using Set and the spread operator is as follows:

const a = [1, 1, 2];
const uniqueValues = [...new Set(a)];
Copy after login

This returns [1, 2] as the unique values within the input array. The Set object automatically filters out duplicate values, and the spread operator (...) converts the set back into an array.

The above is the detailed content of How to Find Unique Values in a JavaScript Array Using `Set`?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template