使用javascript过滤数组中具有最低最近值的所有项目

问题描述 投票:0回答:2

我有一个排序数组是

array = [
    { id: 1, orderTotal: 50000 },
    { id: 3, orderTotal: 50000 },
    { id: 2, orderTotal: 100000 },
    { id: 4, orderTotal: 200000 },
] 

我想找到所有订单总额(如果总价最接近的话)。

这是我的代码

const getNearestOrderValue = (arr, totalPrice) => {
    let nearestItem = [];
    let maxSmaller = 0;
    
    for (const item of arr) {
        if (item?.orderTotal <= totalPrice && item?.orderTotal >= maxSmaller) {
          maxSmaller = item?.orderTotal;
          nearestItem.push(item);
        }
    }
    return nearestItem;
}

如果总价= 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 函数以正确响应?我期待得到任何人的帮助。

javascript arrays
2个回答
0
投票

当您找到更接近的值时,只需重置输出数组即可。不需要循环2*n次,更不需要循环n^2次。

const array = [
    { id: 1, orderTotal: 50000 },
    { id: 3, orderTotal: 50000 },
    { id: 2, orderTotal: 100000 },
    { id: 4, orderTotal: 200000 },
];

const getNearestOrderValue = (arr, totalPrice) => {
    let nearestItem = [];
    let maxSmaller = 0;
    
    for (const item of arr) {
        if (item?.orderTotal <= totalPrice && item?.orderTotal >= maxSmaller) {
          if (item?.orderTotal > maxSmaller) {
            maxSmaller = item?.orderTotal;
            nearestItem = [];
          }
          nearestItem.push(item);
        }
    }
    return nearestItem;
}

console.log(getNearestOrderValue(array, 120000));


0
投票

您可以循环播放两次。一次找到

maxSmaller
项,然后过滤原始数组:

/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/ 
const getNearestOrderValue = (arr, totalPrice) => {
  let maxSmaller = 0;
  for (const item of arr) {
    if (item?.orderTotal <= totalPrice && item?.orderTotal >= maxSmaller) {
      maxSmaller = item?.orderTotal;
    }
  }
  return arr.filter((item) => item?.orderTotal === maxSmaller);
};
console.log(
  getNearestOrderValue(
    [
      { id: 1, orderTotal: 50000 },
      { id: 3, orderTotal: 50000 },
      { id: 2, orderTotal: 100000 },
      { id: 4, orderTotal: 200000 },
    ],
    120000
  )
);
<!-- https://meta.stackoverflow.com/a/375985/ -->    <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.