I have an array with objects inside, like this:
const CurrentSchedule = [
{ name: "jão",
date:"22/10/2022",
hour:"12:00"
},
{ name: "jão",
date:"22/10/2022",
hour:"08:00"
}
]
and i have another array with hours to be used, like this
const hours =["08:00","09:00","10:00","11:00","12:00","13:00","14:00"]
and i want to create an another array with the hours but remove the hours that already are in the array CurrentSchedule. i tried to do a filter, like this
const updatedHours = hours.filter((hour)=> hour !== CurrentSchedule.hour)
but dont work. so, i tried to take only the value of hour from the CurrentSchedule with a map, then make a filter with this new array, but also dont work
const hoursToRemove = [];
CurrentSchedule.map((each)=> hoursToRemove.push(each.hour));
const updatedHours = hours.filter(hour => hour !== hoursToRemove)
dont work either. So i tried to do a for
let updatedHours = [];
for(let i = 0 ; i < CurrentSchedule.lenght ; i ){
updatedHours = hours.filter(hour => hour !== CurrentSchedule[i].hour)
}
return updatedHours
but nothing that i tried worked. someone can help me to solve this problem? I'm a beginner dev.
CodePudding user response:
You could get the used hours first and then filter hours
.
const
currentSchedule = [{ name: "jão", date: "22/10/2022", hour: "12:00" }, { name: "jão", date: "22/10/2022", hour: "08:00" }],
hours = ["08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00"],
used = currentSchedule.map(({ hour }) => hour),
result = hours.filter(h => !used.includes(h));
console.log(result);
CodePudding user response:
You were almost right in your first approach. You have to check each hour of CurrentSchedules though, so one way of approaching this problem is mapping the main object in an array of hours:
const CurrentSchedule = [
{ name: "jão",
date:"22/10/2022",
hour:"12:00"
},
{ name: "jão",
date:"22/10/2022",
hour:"08:00"
}
];
const hours =["08:00","09:00","10:00","11:00","12:00","13:00","14:00"];
console.log(hours.filter(h => !CurrentSchedule.map(x => x.hour).includes(h)))