JavaScript – Remove all duplicate items from an array

Dealing with duplicate elements in an array is a common task in JavaScript. Whether you’re cleaning up data or processing user input, you may often need to remove duplicate values from an array. Let’s explore some of the approaches to remove duplicate values from Array!

Using set()

 A Set is a built-in JavaScript data structure that automatically removes duplicates from the values it contains.

function removeDuplicates(arr) {
  return [...new Set(arr)];
}

// Example usage
const numbers = [1, 2, 3, 2, 4, 1, 5, 6, 3];
const uniqueNumbers = removeDuplicates(numbers);
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5, 6]

Using filter()

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

function removeDuplicates(arr) {
  return arr.filter((value, index, item) =>
    item.indexOf(value) === index
  );
}
const numbers = [1, 2, 3, 2, 4, 1, 5, 6, 3];
const uniqueNumbers = removeDuplicates(numbers);
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5, 6]

Using reduce()

The reduce() method executes a reducer function for array element. The reduce() method returns a single value: the function’s accumulated result.

function removeDuplicates(arr) {
  return arr.reduce((unique, item) =>
    unique.includes(item) ? unique : [...unique, item], []);
}
const numbers = [1, 2, 3, 2, 4, 1, 5, 6, 3];
const uniqueNumbers = removeDuplicates(numbers);
console.log(uniqueNumbers); // Output: [1, 2, 3, 4, 5, 6]

Similar Reads