[英]Given array, write a function that finds the max and return the matching string
I have been given an array and need to write a function mostExpensiveItemName(items) and have it return the largest number in the array and return the items name.我得到了一个数组,需要编写一个 function mostExpensiveItemName(items) 并让它返回数组中的最大数字并返回项目名称。
Example output:示例 output:
mostExpensiveItemName(items) //=> "Creation 3005"
Given array:给定数组:
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
}
]
What I have:我有的:
function mostExpensiveItemName(items) {
if (items.length === 0) return undefined;
let mostExpensive = items.reduce((total, items) => items.price > total.price ? items : total);
return mostExpensive.itemName;
}
My solution works but I was wondering if there was a super elementary way of writing it.我的解决方案有效,但我想知道是否有一种超级基本的编写方式。 With a for loop or max() method使用 for 循环或 max() 方法
I have been given an array and need to write a function mostExpensiveItemName(items) and have it return the largest number in the array and return the items name.我得到了一个数组,需要编写一个函数 mostExpensiveItemName(items) 并让它返回数组中的最大数字并返回项目名称。
Example output:示例输出:
mostExpensiveItemName(items) //=> "Creation 3005"
Given array:给定数组:
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
}
]
What I have:是)我有的:
function mostExpensiveItemName(items) {
if (items.length === 0) return undefined;
let mostExpensive = items.reduce((total, items) => items.price > total.price ? items : total);
return mostExpensive.itemName;
}
My solution works but I was wondering if there was a super elementary way of writing it.我的解决方案有效,但我想知道是否有一种超级基本的编写方式。 With a for loop or max() method使用 for 循环或 max() 方法
function mostExpensiveItemName(items) {
let counter = 0;
//assign name to return later with conditional
let name;
for (let i = 0; i < items.length; i++){
const e = items[i];
/* conditional holds price value in the counter variable
while it cycles through the loop */
if (e.price > counter){
counter = e.price;
//if true, condition also assigns name to e.itemName
name = e.itemsName;
}
}
return name;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.