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
JavaScript Arrays
JavaScript Array Methods
JavaScript Objects
Exercises & Assignments
Write a JavaScript program to find the sum and average of array elements
Write a JavaScript program to find the largest and smallest number in an array
Write a JavaScript program to remove duplicates from an array
Write a JavaScript program to filter even numbers and double them
Write a JavaScript program to count the frequency of words in a sentence
Interview Questions & Answers
What is the difference between map and forEach?
What is the difference between slice and splice?
What is the difference between shallow copy and deep copy in JavaScript?
What is the difference between spread and rest operators?
What are Map and Set in JavaScript?
How do you check if a variable is an array in JavaScript?