How to remove duplicates from JavaScript Array?

How to remove duplicates from JavaScript Array?

one way to remove duplicates is using Set:

let arr=[1,2,2,3,4,5,4,5,6]
const set=new Set(arr)
let brr=[…set]

let array=[4,6,7,7,8,8]
const set =new Set(array)
let newarray=[…set]

in ES5 solution will look something like this:
array.filter(function(element, index){return array.indexOf(element) === index})


Worst approach you follow @sonutj

I guess we should know all sort of approach. Set and Map is in es6. @sadabkhan14198

1 Like

Third method to eliminate duplicates from an array using reduce->
array.reduce((acc, cur)=>acc.includes(cur)? acc : […acc, cur], [ ]);

A single line version using JavaScript array filter and indexOf function:

arr = arr.filter(function (value, index, array) { 
    return array.indexOf(value) === index;

A simple logical soln
const removeDUplicates = (arr)=>{
let sorted = arr.sort()
let unique = []
for(let i = 0; i < sorted.length; i++){
if(sorted[i] !== sorted[i + 1]){

return unique

JavaScript Array.filter() creates a new array filled with elements that pass a test provided by a function.

var myArr = ["One","Two","Two","Three","Four","Four","Five"];
retArr = myArr.filter(function(item, pos) {
    return myArr.indexOf(item) == pos;

Above code iterate over the array and, for each element, check if the first position of this element in the array is equal to the current position . Obviously, these two positions are different for duplicate elements.