Arrange Javascript Arrays

后端 未结 2 753
没有蜡笔的小新
没有蜡笔的小新 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:25

    Here is a solution for you. First of all it creates an array of objects which represent the cars and their associated values (joinCarPrices).

    Then we perform a sort, using the custom sorting function priceSort by using the Array#sort function. Which sorts the cars based on the algorithm you asked for. Lastly, we use Array#slice to only have the 3 highest prices cars.

    var cars = ["Ferrari", "Lamborghini", "Jaguar", "Hummer", "Toyota"],
    price = [12, 34.5, 3.54, 45.9, 3.44],
    result,
    joinCarPrices = function () {
        var index = 0,
            carPrices = [];
    
        for (index = 0; index < cars.length; index++) {
            carPrices[index] = {
                'car': cars[index],
                'price': price[index]
            };
        }
    
        return carPrices;
    },
    priceSort = function (a, b) {
        // If the first car is less than the second car
        if (a.price < b.price) {
            return 1;
        } else if (a.price > b.price) {
            // If the first car is more than the second car
            return -1
        } else {
            // Else sort by the car name
            return a.car < b.car ? -1 : 1;
        }
    };
    
    cars = joinCarPrices(); // Join the Cars/Prices together as Objects, into an array
    result = cars.sort(priceSort); // Sort the Cars based on the Price Sort function
    result = result.slice(0, 3); // Slice to only give us array items 0-3
    console.log(result);
    

    And heres a JSFiddle showing it working!

提交回复
热议问题