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 May 14, 2024 13:38 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

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.

Explore: Online JavaScript Courses and Certifications

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

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
JavaScript Array Sort
The JavaScript array.sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order, but a custom...read more

How to Find the JavaScript Array Length
How to Find the JavaScript Array Length
The length property of a JavaScript array returns the number of elements in the array, providing an easy way to determine its size. It's dynamic, meaning it updates as elements...read more

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
Difference between Java and JavaScript | Java vs Javascript
Java and JavaScript are one of the two most popular programming languages that are used by developers around the globe. In this article, we will discuss the difference between two...read more
Introduction to JavaScript Data Types With Examples
Introduction to JavaScript Data Types With Examples
JavaScript supports several data types including numbers, strings, booleans, arrays, objects, null, and undefined. Numbers represent numeric values, strings represent text, booleans represent true or false values, arrays store multiple...read more

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
JavaScript Functions
A JavaScript function is a block of reusable code designed to perform a particular task, enhancing code efficiency and organization. Functions are invoked or called to execute their defined operations...read more

TypeScript vs JavaScript
TypeScript vs JavaScript
The main difference between TypeScript and JavaScript is that TypeScript is an open-source programming language that supports building large-scale web applications. On the other hand, JavaScript is a scripting language...read more

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