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.
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 =…