There are several ways to remove duplicates from an array in JavaScript.

One way is to use the Set object, which only allows unique values. You can convert the array to a set, and then convert it back to an array using the spread operator (…).
For example:

var fruits = ["apple", "banana", "cherry", "banana", "apple"];
var uniqueFruits = [...new Set(fruits)];
console.log(uniqueFruits); // ["apple", "banana", "cherry"]

Another way to remove duplicates is to use the filter() method along with the indexOf() method.

var fruits = ["apple", "banana", "cherry", "banana", "apple"];
var uniqueFruits = fruits.filter((item, index) => fruits.indexOf(item) === index);
console.log(uniqueFruits); // ["apple", "banana", "cherry"]

You can also use the reduce method to remove duplicates.

var fruits = ["apple", "banana", "cherry", "banana", "apple"];
var uniqueFruits = fruits.reduce((acc, current) => acc.includes(current) ? acc : [...acc, current], []);
console.log(uniqueFruits); // ["apple", "banana", "cherry"]

You can also use the for loop to iterate through the array and use the Array.prototype.includes method to check for duplicates.

var fruits = ["apple", "banana", "cherry", "banana", "apple"];
var uniqueFruits = []
for (var i = 0; i < fruits.length; i++) {
    if (!uniqueFruits.includes(fruits[i])) {
        uniqueFruits.push(fruits[i]);
    }
}
console.log(uniqueFruits); // ["apple", "banana", "cherry"]

Please note that all of the above methods will return a new array with unique elements, but the original array will remain unchanged.

You can use any of the above methods to remove duplicates from an array in JavaScript.

Also Read:

Categorized in: