I am using JSON data from Edmunds car API. Here is a simplified version of the returned data:
[[
{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}
]
]
In this example there are 2 inner arrays that represent the different options of drive train available for this car model (front and all wheel).
I am trying to find the lowest price for each respective drive train and push the object into a new array. In my example I would like the final result to be..
var finalArr = [{drivenWheels: "front wheel drive", price: 32442},{drivenWheels: "all wheel drive", price: 29902}]
I have been trying to solve this for a while now and can't figure it out. Here is what I have so far.
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;
}
If there is 1 inner array. I can get it to work. The problem is when there are 2,3 or 4 inner arrays (representing drive trains). I would like to write a function that can handle any number of drive trains that the API returns. I actually understand why my solution doesn't work. The problem is that I'm new and I've hit a brick wall of understanding. The solution is slightly out of my grasp.
Here are 2 similiar questions that were helpful but they deal with 1 inner array and I still can't figure it out. Any help would be appreciated! Here and Here