我需要从对象列表中找到一个项的索引。首先,我必须检查是否存在状态为WAITING的项目。如果不存在具有该状态的项目,则查找具有任何其他状态的其他项目。有什么更好的解决方案吗?
该代码中的x来自地图
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;
}
不会有任何原因"单线溶液";(在任何情况下都被高估了;难以阅读,难以调试(;但是您可以通过使用for
循环避免在数组中搜索两次:
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;
});
或者,如果你真的想使用findIndex
,你可以通过先找到第一个与slot
匹配的来避免一些搜索:
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;
});
注意,如果orders
是伪的,则上述两个都返回-1
,而不是undefined
。如果你真的想要undefined
,请调整。
您可以使用findIndex
查找状态等于"WAITING"的项目。如果不存在项目,请使用findIndex
返回具有状态的第一个项目。
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));