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
Susan SarandonOriginal
2024-11-10 07:58:031015browse

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)];

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:
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