# Create / filter an array to have only unique elements in it

Paul Shan Thu Aug 31 2017
At some point while coding we all may have searched how to create an array with all unique values in it. Well for an amateur, code for this one can get a little lengthy but bit research on the web can surely help him to write efficient code. In this article we will show you multiple ways to solve this problem, and will also compare their performance; which will make you write not just smaller, but efficient code as well.

## Unique by iterating

var arr=[1,2,3,4,5,4,3,2,1];
function makeUnique(arr){
var uniqueArray=[];
arr.forEach(function(element){
if(uniqueArray.indexOf(element)===-1){
uniqueArray.push(element);
}
})
return uniqueArray;
}

makeUnique() function will return [ 1, 2, 3, 4, 5 ] here. Well, this is a way to filter out the unique elements from an array. It’s pretty short and simple, uses a simple .forEach() loop to iterate through the array and using a .indexOf() function it checks if the element is already pushed or not. The best thing about JavaScript is, it’s evolving really fast. There is a new spec release every year. On 2016, ES7 was released which gave us a function called .includes() to check if an element is there in an array or not. Let’s make a unique array using that function.
var arr= [1, 2, 2, 4, 5, 4, 7, 8, 7, 3, 6];
function makeUnique(arr){
var uniqueArray=[];
for(var i=0;i< arr.length;i++){
if(!uniqueArray.includes(arr[i])){
uniquearray.push(arr[i]);
}
}
return uniqueArray;
}

The .include() method returns ‘true’ or ‘false’ according to the presence of the argument in an given array. Here is a bit more details about it.

### Array.prototype.includes()

arr.includes(SearchingElement);
arr.includes(SearchingElement, IndexOfElement);

SearchingElement: The SearchingElement is the element to be searched for. If you don’t provide the second parameter, it will search this element in the entire array. IndexOfElement:
• From this position in this array the searching for SearchingElement will begin. Negative value will search from the index of array.length + IndexOfElement by ac. Defaults 0.
• For a negative computed index, means (array.length + IndexOfElement ) is less than 0, the entire array will be searched.
• Incase the IndexOfElement is equal or larger than the array’s length, false will be returned & the array will not be searched at all.
Hope you are clear with these two processes mentioned above. Now we will be discussing about the third way of doing the task. The shortest & best way of creating an array having unique values.

## Set

Set is an object whose primary purpose is to store only unique values irrespective of their type. It can be number, string, null, boolean, symbols, undefined or even objects. Syntax:
var mySet = new Set([iterable]);

Lets write the code solving the above problem:
var arr=[1,2,3,4,5,4,3,2,1];
var uniqueArray = Array.from(new Set(arr));

Very simple. Right ? Using set helps forming unique set very easily while writing the shortest code possible for this task. A detailed cover on Set will be provided by VoidCanvas soon.

## Performance check

Doing some test to find the time taken if we run those three processes with a array full with 1000 random numbers. Execution time given below is an average of multiple runs.

### Iteration with forEach()

var arr = [];
for (var i=0, t=1000; i< t; i++) {
arr.push(Math.round(Math.random() * t))
}
function makeUnique(arr){
var uniqueArray=[];
arr.forEach(function(element){
if(uniqueArray.indexOf(element)===-1){
uniqueArray.push(element);
}
})
return uniqueArray;
}
makeUnique(arr);

Performance Stats Approximate execution time: less than 2ms.

### With Array.prototype.includes()

var arr = [];
for (var i=0, t=1000; i<t; i++) {
arr.push(Math.round(Math.random() * t))
}
function makeUnique(arr){
var uniqueArray=[];
for(var i=0;i< arr.length;i++){
if(!uniqueArray.includes(arr[i])){
uniqueArray.push(arr[i]);
}
}
return uniqueArray;
}
makeUnique(arr);

Performance stats Approximate execution time: 1.5 ms

### With Set()

    var arr = [];
for (var i=0, t=1000; i<t; i++) {
arr.push(Math.round(Math.random() * t))
}
var uniqueArray = Array.from(new Set(arr));

Performance Stats Approximate execution time is 3 ms.

## Conclusion

The test been conducted with Node.js 8.4.0. The test results will be different on chrome console (from the second run), duo to JIT compilation in the same thread. Now the question is, the newest technique, i.e. Set seems slower than the others. So is it really the best practice? And moreover, why is a new technique slower? The reason is Set was released in ES6 and V8 (node’s JS engine) people has implemented it to meet the timeline (2015). It functions properly, but not implemented in the best possible and performant way. They are working to make it better. For a reference, you will find Set working more slower in node 7.6.0 (approximately 5ms). So, the recent node is faster and in future it will be more fast.
ArrayCode

Written By

## Paul Shan

• E

• R

• C

• S

### SEO

Search engine optimization

• E

• C

### CMS

wordpress, drupal, jumla, magento and more

Show All

### Tags

vue-js
Web development
vue css
social share buttons
real-life-example
react datetime picker
progra
Online
MathJax
jsfiddle
jquery chart library
instant search using vue
handlebars
event loop
Design
console.log
best practices
imorph

Show All