Thursday, November 29, 2018

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.

How To Get Unique Values In An Array In JavaScript

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"]

This is all about get unique value from an array. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment