I have this array of objects with months and status properties:
const data = [
{
"month": "Jan",
"status": "Full"
},
{
"month": "Feb",
"status": "Full"
},
{
"month": "Mar",
"status": "Full"
},
{
"month": "Apr",
"status": "Full"
},
{
"month": "May",
"status": "Full"
},
{
"month": "Jun",
"status": "Full"
},
{
"month": "Jul",
"status": "Full"
},
{
"month": "Aug",
"status": "Full"
},
{
"month": "Sep",
"status": "Full"
},
{
"month": "Oct",
"status": "Full"
},
{
"month": "Nov",
"status": "Full"
},
{
"month": "Dec",
"status": "Full"
},
]
Basically I would like to know if all of the statuses for each month is "Full". Using every function:
const status = data.every(d => d.status === 'Full');
I’m able to know if all of the months have "Full" statuses. However, I would also like to identify if the month is started at a later date e.g. on April to December, then it would still return true. What would be the best logic for achieving this? What I’ve tried so far:
function identifyStatus(data) {
const status = data.every(d => d.status === 'Full') && data.length;
let finalStatus = false;
if (!status) {
let start = -1;
for (i = 0; i < data.length; i++) {
if (start !== -1) {
if (data[i].status === 'Full' && i !== data.length - 1) {
continue;
} else {
finalStatus = true;
}
} else {
if (data[i].status === 'Full') {
start = i;
}
}
}
}
return finalStatus;
}
Need inputs. Thanks.
>Solution :
If I understand correctly, you want to be able to return true if say, January and February are not "Full" but every subsequent month is "Full".
To do that, I would first find the index where the first "Full" appears, using Array.findIndex.
const firstMonth = data.findIndex(d => d.status === "Full")
Then, if a match exists, create an array slice to iterate over with the every function.
if (firstMonth >= 0) { // findIndex returns -1 in case of no match
const fullMonths = data.slice(firstMonth)
return fullMonths.every(d => d.status === "Full")
}