By Saheb Sutradhar - Updated On 27-02-2024
In this post, I will show you how to remove duplicates from an array in javascript.
1. We can use filter()
method to remove duplicates from array , if the index of the element gets matched with the indexOf value then only that element will get added.
let data = [1, 2, 3, 2, 1];
let uniqueData = data.filter((c, index) => {
return data.indexOf(c) == index;
});
console.log(uniqueData);
Output - [ 1, 2, 3 ]
2. Using we can remove duplicates from an array, Set
is nothing but a collection of unique data, we used a set to convert the array into a Set to remove the duplicates, and then using the spread operator we converted back the Set into an array again.
let data = [1, 2, 3, 2, 1];
let setData= new Set(data);
let uniqueData = [... setData]
console.log(uniqueData);
Output - [ 1, 2, 3 ]
3. Another way to remove duplicates from array. using forEach and includes method.
array.includes(element) if the element is there in the array the include
method will return true
else false
. so below example we are iterating the data array using forEach loop and inside of it we are checking if() uniqueData array has each of the data elements or not, if not then we are pushing that element to the uniqueData array.
let data = [1, 2, 3, 2, 1];
let uniqueData=[];
data.forEach(elem=>{
if(!uniqueData.includes(elem)){
uniqueData.push(elem);
}
})
console.log(uniqueData);
Output - [ 1, 2, 3 ]
You can choose any of the three examples to remove duplicates from the array in your project.
Categories
Trending Posts
Build a JavaScript Carousel Slider With Example...
How to Disable the Submit Button in Formik...
How to Use Bootstrap 5 in Next.js...
What is Multer? How To Handling File Uploads in No...
How to Clear an Array in JavaScript...
How to Check if a Key Exists in a JavaScript Objec...
How to Open All Links in a New Tab Using JavaScrip...
JavaScript Array Filter...
What is the Next.js Image Component...
JavaScript Ternary Operator: A Concise Decision-Ma...
codelearningpoint © 2024