Home > Web Front-end > JS Tutorial > body text

How Can I Get Unique Values From a JavaScript Array?

Patricia Arquette
Release: 2024-11-21 15:15:18
Original
217 people have browsed it

How Can I Get Unique Values From a JavaScript Array?

Unique Values in JavaScript Arrays

To obtain a list of unique values from an array in JavaScript, you can utilize the Set data structure introduced in ES6.

Unlike arrays, Sets store unique elements, eliminating duplicates. Here's a solution using Set and the spread operator (...):

var array = [1, 1, 2];

var uniqueValues = [... new Set(array)];
Copy after login

This code creates a new Set object from the input array and then uses the spread operator to convert it back into an array of unique elements.

This solution has the advantage of being concise and efficient, requiring only a single line of code. It is particularly useful when working with large arrays and can handle arrays containing objects or other complex data types.

The above is the detailed content of How Can I Get Unique Values From a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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