Javascript 数组包含多个包含多个对象的数组

标签 javascript jquery arrays object nested-loops

我正在使用来自 Edmunds 汽车 API 的 JSON 数据。以下是返回数据的简化版本:

[[
 {drivenWheels: "front wheel drive", price: 32442},
 {drivenWheels: "front wheel drive", price: 42492},
 {drivenWheels: "front wheel drive", price: 38652},
 {drivenWheels: "front wheel drive", price: 52402}
 ],
 [{drivenWheels: "all wheel drive", price: 29902},
  {drivenWheels: "all wheel drive", price: 34566},
  {drivenWheels: "all wheel drive", price: 33451},
  {drivenWheels: "all wheel drive", price: 50876}
 ]
]

在此示例中,有 2 个内部数组,代表该车型可用的传动系统的不同选项(前轮和全轮)。

我试图找到每个各自传动系统的最低价格并将对象插入一个新数组。在我的示例中,我希望最终结果是..

var finalArr = [{drivenWheels: "front wheel drive", price: 32442},{drivenWheels: "all wheel drive", price: 29902}]

我已经尝试解决这个问题有一段时间了,但无法解决。这是我到目前为止所拥有的。

function findLowestPriceDrivenWheels(arr){
    var wheelAndPriceArr = [];
    var shortest = Number.MAX_VALUE;
    for (var i = 0; i < arr.length; i++){
        //loops inner array
        for (var j = 0; j < arr[i].length; j++){
            if(arr[i][j].price < shortest){
                shortest = arr[i][j].price;
                wheelAndPriceArr.length = 0;
                wheelAndPriceArr.push(arr[i][j]);
            }
        }  
    }
    console.log(wheelAndPriceArr);
    return wheelAndPriceArr;
}

如果有 1 个内部数组。我可以让它发挥作用。问题是当有 2,3 或 4 个内部阵列(代表传动系统)时。我想编写一个函数来处理 API 返回的任意数量的传动系统。 我实际上明白为什么我的解决方案不起作用。问题是我是新人,我在理解上遇到了障碍。解决方案有点超出我的掌握。

这里有 2 个类似的问题很有帮助,但它们处理 1 个内部数组,我仍然无法弄清楚。任何帮助,将不胜感激! HereHere

最佳答案

假设 arr 是您的 JSON

var results = [];
arr.forEach(function(a,i){a.forEach(function(b){(!results[i]||b['price'] < results[i]['price'])&&(results[i]=b);});});

我是俏皮话的忠实粉丝

结果 (从控制台复制粘贴)

[
    {
        "drivenWheels":"front wheel drive",
        "price":32442
    },
    {
        "drivenWheels":"all wheel drive",
        "price":29902
    }
]
<小时/>

更加直接

var results = [],
    i;

for (i = 0; i < arr.length; i += 1) {
    var a = arr[i],
        j;

    for (j = 0; j < a.length; j += 1) {
        var b = a[j];
        //  !results[i] will check if there is a car for the current drivenWheels. It will return true if there isn't
        if (!results[i] || b['price'] < results[i]['price']) {
            results[i] = b;
        }
    }
}

关于Javascript 数组包含多个包含多个对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29640355/

相关文章:

javascript - 如何获得 overflow hidden 的加载链接并在悬停时显示完整内容?

javascript - 是否可以在一个 div 中有两个 div,一个停靠在左边,一个停靠在右边,这样当空间不可用时,一个会缩小?

javascript - 仅在 Tag-it.js 中为获取的数据创建标签需要验证任何外部数据的创建标签

jquery。如何获得 sibling 的高度?

jquery - 使用 jQuery 更改单个图像源

javascript - 什么是 JavaScript >>> 运算符以及如何使用它?

JQuery/CSS3 : Animating auto height change

c - 为什么这个二分搜索会给我一个无限循环?

javascript - 从 jQuery 事件更新全局变量

javascript - 使用纯 JS 或 jQuery 在 JavaScript 中反序列化 HTML 中的数据