DEV Community

Abu Jaid
Abu Jaid

Posted on • Updated on

How to remove duplicates element from array

In this post i'm going to remove duplicates element from array,i will try with multiple approaches to remove duplicates element from array.

Method 1
Using Set

const array = ["a","b","c","d","a","c","e","f"];
const m1 = [...new Set(array)];
console.log(m1);
// ["a", "b", "c", "d", "e", "f"] 
Enter fullscreen mode Exit fullscreen mode

Method 2
Using object

const array = ["a","b","c","d","a","c","e","f"];
let obj = {};
for (let arr of array){
obj[arr]=true;
}
console.log(Object.keys(obj));
// ["a", "b", "c", "d", "e", "f"] 
Enter fullscreen mode Exit fullscreen mode

Method 3
Using Loop

const array = ["a","b","c","d","a","c","e","f"];
const m3 = [];
for(var i = 0;i<array.length;i++){
const arr = array[i];
m3.indexOf(arr) === -1 && m3.push(arr);
}
console.log(m3)
// ["a", "b", "c", "d", "e", "f"]
Enter fullscreen mode Exit fullscreen mode

Method 4
Using Filter

const array = ["a","b","c","d","a","c","e","f"];
const m4 = array.filter((el,index)=>array.indexOf(el) == index);
console.log(m4);
// ["a", "b", "c", "d", "e", "f"]
Enter fullscreen mode Exit fullscreen mode

Top comments (4)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Another 'using object' one with reduce:

const array = ["a","b","c","d","a","c","e","f"];
console.log(Object.keys(array.reduce((a,v)=>({...a,[v]:1}),{})));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
abu profile image
Abu Jaid

yeah great !

Collapse
 
yaireo profile image
Yair Even Or
Collapse
 
ghamadi profile image
Ghaleb • Edited

Not even close.

For starters, it does not solve the proposed problem (filtering out duplicates); it returns the list of nonunique items.

Second, the time complexity of that solution is O(n2)O(n^2) . For an array of size nn , the filter function needs to run (ni)(n - i) iterations for each element at index ii .

Even if the goal is to return the list of nonunique items - which, again, is not the case here - a solution with O(n2)O(n^2) time complexity is most definitely not the "best".