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));
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.
const newArray = array.reduce((acc, curr) => {
if (!acc.find(obj => JSON.stringify(obj.value) === JSON.stringify(curr.value))) {
acc.push(curr);
}
return acc;
}, []);
console.log(newArray);
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.
const newArray = array.filter((obj, index, self) =>
index === self.findIndex((o) => (
o.value.departure.id === obj.value.departure.id &&
o.value.date.start === obj.value.date.start &&
o.value.type === obj.value.type
))
);
console.log(newArray)
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()