How to Remove Duplicates from JavaScript Array?

How to Remove Duplicates from JavaScript Array?

3 mins read61.6K Views Comment
Chanchal
Chanchal Aggarwal
Senior Executive Content
Updated on Dec 23, 2024 12:26 IST

Entering some items twice is a common problem one can face while entering data in a system. It can be duplicates of names while entering students’ names and numbers or making a checklist of stock present in the shop. Not to worry, there are JavaScript array methods to fix the duplicate issue and get the desired result.

2022_11_Remove-Duplicates.jpg

Removing duplicates from a JavaScript array is a common task to ensure data integrity. Filter(), set(), forEach(), indexOf(), and reduce() are the JavaScript array functions that allow users to remove duplicate items. This blog will familiarize you with how to use each of them and remove duplicates from the JavaScript array with relevant examples.

Let’s learn how to eliminate duplicates with the help of JavaScript array methods.

Explore: Online JavaScript Courses and Certifications

Table of Content

With the Use of filter() Method

The filter() method generates a new array of items that pass the condition we offer. In this case, it will include only those elements that return “true”. Changing the condition of an array can remove duplicate from JavaScript array.


 
<!DOCTYPE html>
<html>
<body>
<p>Original Array: <span id="originalArray"></span></p>
<p>Array without Duplicates: <span id="uniqueArray"></span></p>
<script>
let arr = ["scale", "happy", "strength", "peace", "happy", "happy"];
// Function to remove duplicates from an array
function removeDuplicates(arr) {
return arr.filter((item, index) => arr.indexOf(item) === index);
}
// Display the original array
document.getElementById("originalArray")[removed] = arr;
// Remove duplicates and display the modified array
let uniqueArr = removeDuplicates(arr);
document.getElementById("uniqueArray")[removed] = uniqueArr;
// Also log the result to the console
console.log(uniqueArr);
</script>
</body>
</html>
Copy code

Output:

["scale", "happy", "strength", "peace"]

With the Use of Set() Method

ES6 (ES2015) introduces a new object type for creating collections of unique values that can be accessed via this method.


 
<script>
let arr = ["scale", "happy", "strength",
"peace", "happy", "happy"];
function removeDuplicates(arr) {
return arr.filter((item,
index) => arr.indexOf(item) === index);
}
console.log(removeDuplicates(arr));
</script>
Copy code

Output:

[“scale”, “happy”, “strength”, “peace”]

JavaScript Array Sort

How to Find the JavaScript Array Length

With the Use of forEach() Method

If the item does not exist in the array, we will push it into the newly created array using the forEach() method.


 
<script>
let arr = ["scale", "happy", "strength",
"peace", "happy", "happy"];
function removeDuplicates(arr) {
let unique = [];
arr.forEach(element => {
if (!unique.includes(element)) {
unique.push(element);
}
});
return unique;
}
console.log(removeDuplicates(arr));
</script>
Copy code

Output:

["scale", "happy", "strength", "peace"]

Difference between Java and JavaScript | Java vs Javascript
Introduction to JavaScript Data Types With Examples

With the Use of Reduce() Method

In the reduce() method, the array elements are reduced and combined into a final array based on the reducer function you pass.


 
<script>
let arr = ["scale", "happy", "strength",
"peace", "happy", "happy"];
function removeDuplicates(arr) {
let unique = arr.reduce(function (acc, curr) {
if (!acc.includes(curr))
acc.push(curr);
return acc;
}, []);
return unique;
}
console.log(removeDuplicates(arr));
</script>
Copy code

Output:

["scale", "happy", "strength", "peace"]

JavaScript Functions

TypeScript vs JavaScript

With the Use of indexOf() Method

It is used to determine the index of the first occurrence of an array element using the indexOf() method. If the item does not exist in the new array, we can iterate over the elements in the array. 


 
let arr = ["scale", "happy", "strength",
"peace", "happy", "happy"];
function removeDuplicates(arr) {
let unique = [];
for(i=0; i < arr.length; i++){
if(unique.indexOf(arr[i]) === -1) {
unique.push(arr[i]);
}
}
return unique;
}
console.log(removeDuplicates(arr));
</script>
Copy code

Output:

["scale", "happy", "strength", "peace"]

Explore popular online courses –  

Free JavaScript Courses Online Html Css Javascript Online Courses & Certifications
JavaScript Online Courses and Certifications The Complete JavaScript Course: Beginner to Advanced Level

Conclusion

There can be n reasons for duplicates in content, but you cannot avoid this. To remove this, you can use several functions such as filter(), set(), reduce(), forEach(), and indexof() methods. Using these functions, you can remove duplicates from JavaScript arrays.

Explore more- Top JavaScript interview questions and answers

FAQs

What is the best approach remove duplicates from a JS array?

JavaScript array duplicates can be removed using various functions, it can be filter(), indexof(), reduce, and foreach().

How will you remove duplicates from an array of arrays?

The first step is to convert an array of duplicates into a Set. Duplicate elements will be implicitly removed from the new Set. Duplicate arrays can be removed by converting the set back to an array.

Can you remove duplicates from an array?

We can remove a duplicate element in an array in a temporary array or a separate index. The array must be sorted to remove the duplicate element from the array. You can sort it by calling Arrays. sort(arr) method if an array is not sorted.

How can I remove duplicates from an array using ES6?

Use the Set object combined with the spread operator: const uniqueArray = [...new Set(myArray)]; This method is simple and efficient for arrays containing primitive types.

Can I remove duplicates from an array of objects?

Yes, use the filter method with a helper map to track seen objects based on a unique property (like id): const uniqueArray = myArray.filter((obj, index, self) => index === self.findIndex((t) => (t.id === obj.id)));

About the Author
author-image
Chanchal Aggarwal
Senior Executive Content

Chanchal is a creative and enthusiastic content creator who enjoys writing research-driven, audience-specific and engaging content. Her curiosity for learning and exploring makes her a suitable writer for a variety ... Read Full Bio