29-Aug-2022
.
Admin
Hi friends,
This post will give you an example of how to remove duplicate objects in array node.js. you can understand the concept of remove duplicate objects in array node.js. We will look at an example of remove duplicate objects in array nodejs. you can see remove duplicate objects in the array node.js example. you will do the following things for node.js remove duplicate objects in the array.
I will give you an example in remove duplicate objects from the array. I will use Array.filter() remove duplicate objects from array. Array.filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ({id} destructs the object into only its id). To only filter out actual duplicates, it is using Array.includes()'s second parameter fromIndex with index + 1 which will ignore the current object and all previous.
So, let's start follwing example with output:
Step 1: Create Node.js Project
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
Step 2: Update index.js File
index.js
// create object list
arr =[
{
id: 1, name: 'one'
},
{
id: 2, name: 'two'
},
{
id: 1, name: 'one'
}
]
// get id in object list
ids = arr.map(o => o.id)
// filtered remove duplicate objects from array
filtered = arr.filter(({id}, index) => !ids.includes(id, index + 1))
console.log(filtered)
Output:
[ { id: 2, name: 'two' }, { id: 1, name: 'one' } ]
I hope it can help you...
#Node JS