DEV Community

skptricks
skptricks

Posted on

How To Get Unique Values In An Array In JavaScript

Post Link : How To Get Unique Values In An Array In JavaScript

In this tutorial we are going to discuss how to get unique values in an array in javascript. Lets see the below examples for more information.

Method-1 :
In this example, we are using Set keyword with Array,from of ES6 feature. A Set is a collection of values, where each value may occur only once.

let values = ["Sumit", "Amit", "Neeraj", "Alex", "Skp", "Sumit", "Sam", "Neeraj", "Obama"];

function unique(arr) {
return Array.from(new Set(arr))

}

console.log(unique(values))

Output :

Array ["Sumit", "Amit", "Neeraj", "Alex", "Skp", "Sam", "Obama"]

Method-2 :
In this example, we are using Set keyword with spread operator of ES6 feature. A Set is a collection of values, where each value may occur only once.

let values = ["Sumit", "Amit", "Neeraj", "Alex", "Skp", "Sumit", "Sam", "Neeraj", "Obama"];

function unique(arr) {
return [...new Set(arr)]
}

console.log(unique(values))

Output :

Array ["Sumit", "Amit", "Neeraj", "Alex", "Skp", "Sam", "Obama"]

Top comments (0)