简体   繁体   English

返回对象数组中的最大数

[英]Returning the biggest number in an array of Objects

im trying to figure out how i can return the most expensive price in this array of items.我试图弄清楚如何才能在这一系列商品中返回最昂贵的价格。

let items = [
    {
      itemName: "Effective Programming Habits",
      type: "book",
      price: 13.99
    },
    {
      itemName: "Creation 3005",
      type: "computer",
      price: 299.99
    },
    {
      itemName: "Finding Your Center",
      type: "book",
      price: 15.00
    }
  ]

I know the.reduce() method is specific for arrays.我知道 .reduce() 方法特定于 arrays。 But im not sure what else i could use to determine what the most expensive price is.但我不确定我还能用什么来确定最贵的价格是多少。

I have also tried using Math.max() but im not quite sure how i would use it in this case我也尝试过使用 Math.max() 但我不太确定在这种情况下我将如何使用它

You can use您可以使用

Math.max(...items.map(item => item.price));

to get the highest price.以获得最高的价格。

Using .reduce :使用.reduce

 const items = [ { itemName: "Effective Programming Habits", type: "book", price: 13.99 }, { itemName: "Creation 3005", type: "computer", price: 299.99 }, { itemName: "Finding Your Center", type: "book", price: 15.00 } ]; const mostExpensiveItem = items.reduce((acc,item) => { const maxPrice = acc.price || Number.MIN_VALUE; if(item.price > maxPrice) acc = item; return acc; }, {}); console.log(mostExpensiveItem); console.log(mostExpensiveItem.price);

Using for-loop :使用for-loop

 const items = [ { itemName: "Effective Programming Habits", type: "book", price: 13.99 }, { itemName: "Creation 3005", type: "computer", price: 299.99 }, { itemName: "Finding Your Center", type: "book", price: 15.00 } ]; let mostExpensiveItem = {}; for(let i = 0; i < items.length; i++) { const item = items[i]; const maxPrice = mostExpensiveItem.price || Number.MIN_VALUE; if(item.price > maxPrice) mostExpensiveItem = item; } console.log(mostExpensiveItem); console.log(mostExpensiveItem.price);

Note: If you're only looking for the price , then, you can keep track of this property as a number instead of the whole object.注意:如果您只是在寻找price ,那么您可以将此属性作为数字而不是整个 object 来跟踪。

Use map and Math.max使用mapMath.max

 let items = [ { itemName: "Effective Programming Habits", type: "book", price: 13.99 }, { itemName: "Creation 3005", type: "computer", price: 299.99 }, { itemName: "Finding Your Center", type: "book", price: 15.00 } ] const exp = Math.max(...items.map(({ price }) => price)); console.log(exp)

Try below snippet试试下面的片段

let index,highest = 0;

for ( let item in items ) {
    if(items[item].price > highest ) {
    index  = item;
    highest = items[item].price;
 }
} 
// highest price item
console.log(items[index].price)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM