I have an array like this:
const array =[
{
"value": {
"departure": {
"id": "1203548"
},
"date": {
"start": "2023-11-09",
"end": ""
},
"type": "1"
},
"time": 1699004845364,
"expire": 1699488000000
},
{
"value": {
"departure": {
"id": "1203548"
},
"date": {
"start": "2023-11-09",
"end": ""
},
"type": "1"
},
"time": 1699004845364,
"expire": 1699488000000
},
{
"value": {
"departure": {
"id": "1203549"
},
"date": {
"start": "2023-11-08",
"end": ""
},
"type": "2"
},
"time": 1699004845389,
"expire": 1699489000000
}
]
I am going to remove the duplicates objects that the value field is the same as other objects.
i have tried the following code but it is not based on the value field.
const uniq = new Set(array.map(e => JSON.stringify(e)));
const result = Array.from(uniq).map(e => JSON.parse(e));
2
Answers
Note: This checks for duplicates based on the value field’s entire object structure. If you only want to check a specific field within the value field, you can modify it accordingly.
one more way is to use filter method to check for unique values. The filter method takes a callback function as an argument which will be used to filter the array. Inside this callback function, use the indexOf and lastIndexOf methods to check if the current object is the first or last instance of the same "value" field.
You could use the library lodash this includes functions to remove duplicates from an array for this there would be the method uniq(array) alternatively you can also use the function uniqBy()