查找最大和最小内部对象数组

时间:2014-10-24 12:51:38

标签: javascript arrays algorithm sorting

我有数组,我们称之为fruit_shop,其中包含一堆水果。 水果是3个参数的对象,名称,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 }];

P.S。我正在使用javascript。

3 个答案:

答案 0 :(得分:1)

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;
});

其余部分应该是显而易见的。

并且不要忘记,不止一种水果可能会有最低股价。

答案 1 :(得分:0)

一种选择是按unit_price排序数组,而第一项是最高价,最后一项是最低价

fruit_shop.sort(function (a, b) {
 return b['unit_price'] - a['unit_price'];
});

max = fruit_shop[0];
min = fruit_shop[fruit_shop.length - 1];

答案 2 :(得分:0)

var maxIdx = 0;
var i = 0;
for (var i = 0; i<fruit_shop.length;i++){
     if((fruit_shop[maxIdx].unit_price*fruit_shop[maxIdx].stock)<(fruit_shop[i].unit_price*fruit_shop[i].stock)){
        maxIdx = i;
     }
}
// now maxIdx contains index of the entry with highest unitprice*stock
Alex G的解决方案是有效的,但是排序至少是O(n * log(n))操作,而单个循环总是O(n)。对于小型阵列来说可能微不足道,但对于大型阵列来说可能非常不同

相关问题