Languages
[Edit]
EN

JavaScript - get unique values in array

0 points
Created by:
Nathanial-Donald
524

In this article, we would like to show you how to get unique values in a JavaScript array.

The below example presents the use of Set object that lets us store unique values of any type.

The constructor of Set takes an iterable object and the spread operator (...) transforms the Set object back into the array.

Runnable example:

// ONLINE-RUNNER:browser;

let array = ['A', 'B', 'B', 'B', 'C', 'C'];

let unique = [...new Set(array)];

console.log(unique); // ['A', 'B', 'C']

Second example: 

// ONLINE-RUNNER:browser;

let array = [1, 1, 'B', 'B', 'C', 'C'];

let unique = [...new Set(array)];

console.log(unique); // [1, 'B', 'C']

Note:

Sets are a new object type introduced in ES6 (ES2015).

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join