Remove Duplicates From An Array In JavaScript

To remove duplicates from an array in JavaScript, you can use any of these methods –

  1. Use the Array.filter() method to filter out all the unique elements from the array.
  2. Use the Set() method to get the unique elements from the array.

Let’s discuss each of these methods in detail below.

Remove Duplicates From An Array In JavaScript

remove duplicates from an array in javascript

Array.filter() Method To Remove Duplicates From An Array In JavaScript

The Array.filter() method filters an array based on a condition specified in the callback function.

It tests each element of the array against the condition and returns a new array with only those elements that pass the test.

We can use it to remove duplicates from an array as shown below –

let fruits = ["apple", "orange", "apple", "banana"];  

let uniqueArray = [];

const duplicateFilter = fruits.filter(element => {

if(!uniqueArray.includes(element)) {

  uniqueArray.push(element);

  return true;

 }

 return false;

});

console.log(duplicateFilter)

// Output: ["apple", "orange", "banana"]

In the code above, we have declared an array of fruits and a new uniqueArray variable.

We have passed the Array.filter() method a callback function that tests each element of the fruits array for uniqueness against the elements in the uniqueArray using the JavaScript Array.includes() method.

If an element is not found to be unique, it is filtered out.

If the element is unique, it is pushed to the uniqueArray and filtered in.

The Set() Method To Remove Duplicates From An Array In JavaScript

A Set object is a collection of unique values.

It can be used to remove duplicates from an array by converting the array into a Set and then converting it back to an array as shown below –

let fruits = ["apple", "orange", "apple", "banana"]; 

const uniqueArray = Array.from(new Set(fruits));

console.log(uniqueArray);

// Output: ["apple", "orange", "banana"]

// Output: [“apple”, “orange”, “banana”]

You can also use the … operator to convert the Set back to an array as shown below –

let fruits = ["apple", "orange", "apple", "banana"]; 

const uniqueArray = [...new Set(fruits)];

console.log(uniqueArray);

// Output: ["apple", "orange", "banana"]

Both of these methods will give you the same output – an array containing only unique values.

You can use either method depending on your preference.

Which Method To Use?

If you are working with a large array, it is better to use the Set() method as it is more efficient.

If you are working with a small array, you can use either method.

I hope this article was helpful.

Thanks for reading!

Leave a Reply