I need to find index of an item from a list of objects. First I have to check if that item exist with status of WAITING. If no item with that status exist, then find something else with any other status. Is there any better solution for this?
x in this code coming from a map
MainArray.map((x) => {
let itemIndex = orders?.findIndex(item => item.status === 'WAITING' && item.slot=== (x));
if (itemIndex === -1) {
itemIndex = orders && orders.findIndex(item => item.slot === (x));
}
return itemIndex;
}
There won't be a reasonble "single line solution" (those are over-rated in any case; hard to read, hard to debug); but you can avoid searching through the array twice by using a for loop:
const indexes = MainArray.map((x) => {
let bySlotIndex;
for (let index = 0, length = orders?.length; orders && index < length; ++index) {
const order = orders[index];
if (item.slot === x) {
bySlotIndex = bySlotIndex ?? index;
if (item.status === "WAITING") {
return index; // Found a waiting one, we're done
}
}
}
return bySlotIndex ?? -1;
});
Or if you really want to use findIndex, you can avoid some searching by finding the first one with a matching slot first:
const indexes = MainArray.map((x) => {
const bySlotIndex = orders?.findIndex(order => order.slot === x) ?? -1;
if (bySlotIndex === -1) {
return -1;
}
const waitingIndex = orders.findIndex(
order => order.status === 'WAITING' && order.slot === x,
bySlotIndex // Start at the first one with a matching slot
);
return waitingIndex === -1 ? bySlotIndex : waitingIndex;
});
Note that both of the above return -1 if orders is falsy, rather than undefined. Tweak if you really wanted undefined.
You can use findIndex to look for an item with status equal to 'WAITING'. in case, no item exists, use findIndex to return the first item with a status.
const arr = [{status: "WAITING", slot : 1}, {status: "NOTWAITING", slot: 2}];
const getIndex = (arr) => {
const idx = arr.findIndex(x => x.status === 'WAITING');
return idx !== -1 ? idx : arr.findIndex(x => x.status);
}
console.log(getIndex(arr));