从对象数组中获取匹配的范围项javascript

k4aesqcs  于 2023-01-08  发布在  Java
关注(0)|答案(1)|浏览(144)

我有一个数组命名为层和一个数量变量。现在我试图从我的层数组中获取匹配的范围值。基于匹配的结果,我想计算折扣。我尝试使用find方法,但它给了我一个意外的输出。

实际产量{id: 1, discount_percent:0, quantity:6, title:"Tier 1"}
预期产量{id: 3, discount_percent:10, quantity:10, title:"Tier 3"}

let tiers = [
   {id: 1, discount_percent:0, quantity:6, title:"Tier 1"},
   {id: 2, discount_percent:5, quantity:8, title:"Tier 2"},
   {id: 3, discount_percent:10, quantity:10, title:"Tier 3"},
   {id: 4, discount_percent:12, quantity:12, title:"Tier 4"},
   ...
]
function calculateDiscount(){
   const ordersQuanity = 10;
   const tier = tiers.find((_tier) => _tier.quantity <= ordersQuanity);
   ...
}
j5fpnvbx

j5fpnvbx1#

对于具有discount_percent s和quantity s的多个对象的一般情况,.find不是正确的方法,因为它会在找到匹配项后立即停止。考虑.reduce-如果正在迭代的元素通过了测试 * 并且 * 它的discount_percent大于累加器中的当前元素(如果累加器中有任何内容可以作为开始),则将其返回。

let tiers = [
   {id: 1, discount_percent:0, quantity:6, title:"Tier 1"},
   {id: 2, discount_percent:5, quantity:8, title:"Tier 2"},
   {id: 3, discount_percent:10, quantity:10, title:"Tier 3"},
   {id: 4, discount_percent:12, quantity:12, title:"Tier 4"},
]
function calculateDiscount(){
   const ordersQuanity = 10;
   const bestTier = tiers.reduce((a, tier) => (
     tier.quantity <= ordersQuanity && (!a || tier.discount_percent > a.discount_percent)
       ? tier
       : a
   ), null) || tiers[0]; // alternate with the first element of the array
   // if you want to default to that tier even if the quantity isn't sufficient
   console.log(bestTier);
}
calculateDiscount();

如果你碰巧能够假设每增加一个discount_percent就带来一个更大的数量,并且数组是排序的,那么如果你先反转数组,你就可以使用.find(这样,具有最大discount_percent的项会先被迭代)。

let tiers = [
   {id: 1, discount_percent:0, quantity:6, title:"Tier 1"},
   {id: 2, discount_percent:5, quantity:8, title:"Tier 2"},
   {id: 3, discount_percent:10, quantity:10, title:"Tier 3"},
   {id: 4, discount_percent:12, quantity:12, title:"Tier 4"},
];
const tiersReversed = [...tiers].reverse();
function calculateDiscount(){
   const ordersQuanity = 10;
   const tier = tiersReversed
     .find((_tier) => _tier.quantity <= ordersQuanity)
      || tiers[0]; // alternate with the first element of the array
   // if you want to default to that tier even if the quantity isn't sufficient
   console.log(tier);
}
calculateDiscount();

相关问题