Get all unique values in a JavaScript array

109    Asked by the_4524 in Java , Asked on Sep 4, 2025

How can you get all unique values from a JavaScript array, and what are the different methods to achieve this? Explore approaches like using Set, filter(), or reduce() to remove duplicates and work with clean, distinct data.

Answered by LindaRobinson

Getting all unique values from a JavaScript array is a very common task, especially when working with large datasets where duplicates can easily appear. Thankfully, JavaScript provides multiple ways to handle this efficiently. The goal is to remove duplicates and end up with a clean array of distinct values.

One of the easiest and most modern methods is by using the Set object, which automatically stores unique values. For example:

let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers); // [1, 2, 3, 4, 5]

Other approaches include:

Using filter() and indexOf():

 let arr = [1, 2, 2, 3, 4, 4, 5];
let unique = arr.filter((value, index) => arr.indexOf(value) === index);
console.log(unique); // [1, 2, 3, 4, 5]

Using reduce():

 let arr = [1, 2, 2, 3, 4, 4, 5];
let unique = arr.reduce((acc, curr) => {
  if (!acc.includes(curr)) acc.push(curr);
  return acc;
}, []);
console.log(unique); // [1, 2, 3, 4, 5]

With ES6 Spread and Set (most preferred): Quick, clean, and efficient for modern JavaScript.

 In short, if you’re working with modern JavaScript, using Set is the most efficient and readable way. But if you want more control, filter() or reduce() give you flexibility.



Your Answer

Interviews

Parent Categories