How to remove duplicate items from an array using Javascript?

 Solution: 

Pictorial Presentation


We can remove duplicate items from an array in the following Methods:

1) Using Set with spread operator:

let array = [1,2,3,4,3,2,2,3,4,5]

console.log([...new Set(array)])

output: [1,2,3,4,5]

2) Using Filter Method:

let array = [1,2,3,4,3,2,2,3,4,5]

let newArray = array.filter((element, i)=>  i === array.indexOf(element))

console.log(newArray)

output: [1,2,3,4,5]

Note: We can use reduce and some methods to remove duplicate items of the array but it is a little complex as compared above two methods.


Post a Comment

0 Comments

Close Menu