JavaScript

How to Get All Unique Values in a JavaScript Array

In this tutorial, we are going to see how to get all unique values in a JavaScript array. With JavaScript/ECMAScript 5, you are able to use the filter() method to obtain an array with unique values. So with JavaScript/ECMAScript 6, you can use the “Set” object to get an array with unique values. As shown in the example below:
 

How to Get All Unique Values in a JavaScript Array on ES5
function getUniqueVal(value, index, self) { 
    return self.indexOf(value) === index;
}

var arr = [1, 2, 3, 'w', 3, 'w'];
var newArr = arr.filter( getUniqueVal ); 
console.log(newArr); 

Output:

[1, 2, 3, "w"]

 

 

How to Get All Unique Values in a JavaScript Array on ES6

ECMAScript 6 has a native object called “Set” to save unique values. To get an array with unique values, do the following:

var arr = [1, 2, 3, 'w', 3, 'w'];

let newArr = [...new Set(arr)]; 

console.log(newArr);

Output:

[1, 2, 3, "w"]

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *