Remove Duplicates from Arrays and Strings in JavaScript

habtesoft
2 min readNov 20, 2024

Removing duplicates from arrays and strings is a common task in JavaScript, and there are multiple efficient ways to handle it. Here are some methods to help you remove duplicates from both arrays and strings.

Not a Medium member? Read this article here

1. Removing Duplicates from Arrays

Method 1: Using Set

The Set object in JavaScript automatically removes duplicate values. This makes it a straightforward solution.

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

Method 2: Using filter()

The filter method can be combined with indexOf to only keep the first occurrence of each element.

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5]

Method 3: Using reduce()

Using reduce, you can build a new array that only includes unique elements.

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray =…

--

--

habtesoft
habtesoft

Written by habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat

No responses yet