Write a JavaScript program to remove duplicates from an array

Description: Remove the duplicates from [1, 2, 2, 3, 4, 4, 5].

Hint:

  • A Set keeps only unique values.

JavaScript program to remove duplicates

const items = [1, 2, 2, 3, 4, 4, 5];

const unique = [...new Set(items)];
console.log(unique);

const unique2 = items.filter((x, index) => items.indexOf(x) === index);
console.log(unique2);

Output:

Tutorials Class - Output Window

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

How it works

  • new Set(items) removes duplicates, and [...set] turns it back to an array.
  • The second way keeps an item only if its first position is the current position.

Read Map and Set.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.