I can't get this result: I need to have a date table (in YYYY-MM-DD format), where each date would contain requests. Let me explain, basically I browse an already existing date table, which contains the dates of my requests. And after this date array browsing, I build my new array which contains the date on which the array is positioned, as a key, and the associated request obtained by the call to my API.
So I have an array of the style (in the code snippet, dateArray[i] corresponds to the date on which the date array is positioned):
Here is the table daysRequests:
[{
date: dateArray[i],
requests: [idRequestX]
},
{
date: dateArray[i],
requests: [idRequestX, idRequestY]
}]
And here is the push I do there:
this.daysRequests.push({
day: dateArray[i],
requests: [idRequest]
});
Currently the push in the array creates duplicates for me, because if a date has several requests, it is not able to look for the record in the array corresponding to the already existing date and add in the requests sub-array, the new request.
I don't know how to check that the date already exists in the table and if it does, add the id of the new request in its sub table.
The complexity is that it is a key-value dictionary containing an array.
And that, I can't manage.
Does anyone have an idea?
CodePudding user response:
Use a function to search for the item with the same date. If it doesn't exist you can push the object, if it exists then push just the idRequest
to requests
.
const index=this.daysRequest.findIndex((item) => item.day===dateArray[i]);
if (index==-1){ //index is -1 if the item isn't found
this.daysRequest.push({
day: dateArray[i],
requests: [idRequest]
});
}else{ //index is the index of daysRequest where your date is
this.daysRequest[index].requests.push(idRequest);
}
We can see that the day "Mon Nov 14 2022 00:00:00 GMT 0100" is duplicated, but with 2 different requests, instead of being combined
CodePudding user response:
You can achieve this by using Array.findIndex()
method along with Destructuring assignment
operator.
Live Demo :
const arr = [{
date: '15-11-2022',
requests: [1]
}, {
date: '10-11-2022',
requests: [1, 3]
}];
const objToPush = {
date: '15-11-2022',
requests: [5]
};
const index = arr.findIndex(item => item.date === objToPush.date);
if (index === -1) {
arr.push(objToPush);
} else {
arr[index].requests = [...arr[index].requests, ...objToPush.requests]
}
console.log(arr);