我正在使用来自 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 个内部数组,我仍然无法弄清楚。任何帮助,将不胜感激! Here 和 Here
最佳答案
假设 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/