JavaScript Development Space

How to Remove Duplicate Elements from an Array in JavaScript

When working with arrays in JavaScript, you might encounter situations where you need to remove duplicate elements. This is a common task, and there are several efficient ways to achieve it. In this article, we'll explore different methods to remove duplicates from an array, ranging from simple techniques to more advanced approaches.

1. Using Set

ts
1 const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8];
2 const uniqueArray = [...new Set(arrayWithDuplicates)];
3
4 console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

2. Using \filter() and \indexOf()

ts
1 const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8];
2 const uniqueArray = arrayWithDuplicates.filter((item, index) => {
3 return arrayWithDuplicates.indexOf(item) === index;
4 });
5
6 console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

3. Using \reduce()

ts
1 function removeDuplicates(arr: string[]): string[] {
2 const unique = arr.reduce(function (acc, curr) {
3 curr.trim();
4 if (!acc.includes(curr)) {
5 acc.push(curr);
6 }
7 return acc;
8 }, []);
9 return unique;
10 }

4. Using \forEach() and \includes()

ts
1 const arrayWithDuplicates = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8];
2 const uniqueArray = [];
3
4 arrayWithDuplicates.forEach((item) => {
5 if (!uniqueArray.includes(item)) {
6 uniqueArray.push(item);
7 }
8 });
9
10 console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6, 7, 8]

5. Using Map

ts
1 const arrayWithDuplicates = [
2 { id: 1, name: 'One' },
3 { id: 2, name: 'Two' },
4 { id: 1, name: 'Three' },
5 { id: 3, name: 'Four' },
6 ];
7
8 const uniqueArray = [...new Map(arrayWithDuplicates.map((item) => [item.id, item])).values()];
9
10 console.log(uniqueArray);
11 // Output: [
12 // { id: 1, name: 'Alice' },
13 // { id: 2, name: 'Bob' },
14 // { id: 3, name: 'Charlie' }
15 // ]
JavaScript Development Space

Follow JavaScript Development Space

Stay updated with the latest trends, tutorials, and best practices in JavaScript development. Follow our JavaScript Development blog for expert insights, coding tips, and resources to enhance your web development skills.

© 2024 JavaScript Development Blog. All rights reserved.