我有一个数组,我们称它为 fruit_shop,其中包含一堆水果。 水果是具有 3 个参数的对象,name、unit_price、stock;它代表水果的名称、商店的库存和当前的单价。 我需要找出哪个水果有最大/最小库存,哪个有最大值[unit_price*stock]。
fruit_shop = [
{ name: "Apple",unit_price: 100, stock:5 },
{ name: "Mango",unit_price: 120, stock:4 },
{ name: "Orange",unit_price: 90, stock:6 }];
附言我正在使用 javascript。
最佳答案
var fruit_shop = [
{ name: "Apple", unit_price: 100, stock:5 },
{ name: "Mango", unit_price: 120, stock:4 },
{ name: "Orange", unit_price: 90, stock:6 }
];
var stock = fruit_shop.map(function(x){
return x.stock;
});
var max = Math.max.apply(null, stock);
var maxfruit = fruit_shop.reduce(function(fruits, fruit){
if(fruit.stock === max)
fruits.push(fruit);
return fruits;
}, []);
// Edit: I forgot about filter. Reduce is more general,
// but for collecting values, filter is simpler.
var maxfruit = fruit_shop.filter(function(fruit){
return fruit.stock === max;
});
其余部分应该是显而易见的。
并且不要忘记,不止一种水果可能有最低库存价格。
关于javascript - 查找对象的最大和最小内部数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26548263/