Home >Web Front-end >JS Tutorial >How Can I Get Unique Values From a JavaScript Array?

How Can I Get Unique Values From a JavaScript Array?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-21 15:15:18341browse

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

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!

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