我正在使用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返回的任意数量的驱动器系列的函数。 我实际上理解为什么我的解决方案不起作用。问题在于我是新人,而且我已经达到了理解的难度。解决方案略微不受我的掌握。
答案 0 :(得分:1)
使用underscore.js(http://underscorejs.org/)
更容易arr = [
[
{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}
]
]
_.map(arr, function(items){
return _.chain(items)
.sortBy(function(item){
return item.price
})
.first()
.value();
})
答案 1 :(得分:1)
假设 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;
}
}
}