我有一个已排序的数组如下:
array = [
{ id: 1, orderTotal: 50000 },
{ id: 3, orderTotal: 50000 },
{ id: 2, orderTotal: 100000 },
{ id: 4, orderTotal: 200000 },
]
我想找到与某个总价最接近的所有订单总额。
这是我的代码:
const getNearestOrderValue = (arr, totalPrice) => {
let nearestItems = [];
let minDifference = Infinity;
for (const item of arr) {
const difference = Math.abs(item.orderTotal - totalPrice);
if (difference <= minDifference) {
minDifference = difference;
nearestItems = [item]; // 重置结果数组,只保留与当前最小差值相等的项
} else if (difference === minDifference) {
nearestItems.push(item); // 如果找到多个具有相同最小差值的项,则将其添加到结果数组中
}
}
return nearestItems;
}
如果总价为 80000,我的代码将正确返回结果:
[
{ id: 1, orderTotal: 50000 },
{ id: 3, orderTotal: 50000 },
]
但如果总价是 120000,我的代码返回的结果是:
[
{ id: 1, orderTotal: 50000 },
{ id: 3, orderTotal: 50000 },
{ id: 2, orderTotal: 100000 }
]
而我想要的结果是:
[
{ id: 2, orderTotal: 100000 }
]
我应该如何修改 getNearestOrderValue
函数以得到正确的响应呢?我期待收到任何人的帮助。