Arrange Javascript Arrays

后端 未结 2 732
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 13:11

I have array of cars and an array of price corresponding to each car.

I want to implement the function highest3 which will return an array of 3 cars in order by their p

2条回答
  •  余生分开走
    2021-01-26 13:30

    This is only one possible solution:

    //I assume you get the arrays correctly linked i.e price[0] is the 
    //price of cars[0]
    var cars = ["Ferrari", "Lamborghini", "Jaguar", "Hummer", "Toyota"];
    var price = [12, 34.5, 3.54, 45.9, 3.44];
    
    result == ["Hummer", "Lamborghini", "Ferrari"];
    
    function highest3 (cars, price) {
    
    //First we unite the two arrays 
    carsAndPrice = [];
    for (var i = 0; i < cars.length; i = i +1)
        carsAndPrice[i] = {car:cars[i],price:price[i]};
    }
    //Now that the price and the cars are strongly linked we sort the new array
    //I'm using bubble sort to sort them descending this seems to be more of 
    //a beginner question
    var swapped;
        do {
            swapped = false;
            for (var j=0; j < carsAndPrice.length-1; i++) {
                if (carsAndPrice[i].price < carsAndPrice[i+1].price) {
                    var temp = carsAndPrice[i];
                    carsAndPrice[i] = a[i+1];
                    carsAndPrice[i+1] = temp;
                    swapped = true;
                }
            }
        } while (swapped);
      //return the name of the first 3 cars from the array
      var result = [];
      result[0] = carsAndPrice[0].price; //Most expensive
      result[1] = carsAndPrice[1].price;
      result[2] = carsAndPrice[2].price;
      }
    

提交回复
热议问题