3 Best ways to remove duplicates from array in Javascript





Hey guys in post we will discuss the 3 best ways to remove duplicates from array in javascript. so let’s begin

  • By using Set
  • By using Filter
  • By using ForEach

Let’s look at the examples one by one

By using Set()


The Set object lets you store unique values of any type, whether primitive values or object references.

Set objects are collections of values. You can iterate through the elements of a set in insertion order. A value in the Set may only occur once; it is unique in the Set’s collection.

Let’s look at the example

let numbers = [5, 9, 5, 1, 2, 9, 0];
let uniqueNumbers = [...new Set(numbers)];
console.log(uniqueNumbers);

output: [5, 9, 1, 2, 0]

Further read on Set at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

By using filter()


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

Let’s look at the example

let numbers = [5, 9, 5, 1, 2, 9, 0];
let uniqueNumbers = numbers.filter((number, index) => {
  return numbers.indexOf(number) === index;
})
console.log(uniqueNumbers);

output: [5, 9, 1, 2, 0]

Further read on filter() at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

By using foreach()


The forEach() method executes a provided function once for each array element.

Let’s look at an example

let numbers = [5, 9, 5, 1, 2, 9, 0];
let uniqueNumbers = [];
numbers.forEach((number) => {
  if(!uniqueNumbers.includes(number)) {
    uniqueNumbers.push(number);
  }
})
console.log(uniqueNumbers);

output: [5, 9, 1, 2, 0]

Further read on forEach() at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply