【问题标题】:Given array, write a function that finds the max and return the matching string给定数组,编写一个查找最大值并返回匹配字符串的函数
【发布时间】:2021-01-25 10:55:00
【问题描述】:

我得到了一个数组,需要编写一个函数 mostExpensiveItemName(items) 并让它返回数组中的最大数字并返回项目名称。

示例输出:

mostExpensiveItemName(items) //=> "Creation 3005"

给定数组:

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
  }
]

我有什么:

function mostExpensiveItemName(items) {
  if (items.length === 0) return undefined;
  let mostExpensive = items.reduce((total, items) => items.price > total.price ? items : total);

  return mostExpensive.itemName;
}

我的解决方案有效,但我想知道是否有一种超级基本的编写方式。使用 for 循环或 max() 方法

【问题讨论】:

  • 你所拥有的似乎已经足够了。
  • 我还要说您的解决方案是可行的方法。它很短,很容易阅读(即使我将 (total, items) 重命名为 (curMax, item))并且运行在 O(n) 中。我会考虑将它抽象一层,创建一个customMax(items, item => item.price) 方法,特别是如果您在多个场合使用它。

标签: javascript arrays


【解决方案1】:

您可以尝试升序 sort 并选择最后一个元素

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.0,
  },
]

function mostExpensiveItemName(items) {
  return (items.sort((a, b) => a.price - b.price).pop() || {}).itemName
}

console.log(mostExpensiveItemName(items))
console.log(mostExpensiveItemName([]))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    • 2020-08-07
    • 1970-01-01
    • 2014-05-07
    • 2022-10-02
    • 1970-01-01
    • 2022-11-15
    相关资源
    最近更新 更多