2014-02-08 88 views
0

我有一系列的汽车和价格对应于每辆车的阵列。排列Javascript阵列

我想实现函数highest3,它将按照它们的价格(从最高到最低)依次返回3辆车的数组。

但是,如果价格相等,则按字母顺序返回汽车。

在下面的例子中,“悍马”将是第一个条目。

代码

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) { 

//Please help me here. 

} 

有人可以帮我实现highest3功能?我是一个新手。谢谢。

+0

的可能重复的[JavaScript的 - 按基于整数的另一个阵列的阵列(http://stackoverflow.com/questions/4046967/javascript-sort-an-array-based-on-another-array-of-整数) – sachleen

+0

这看起来很像功课。 –

+1

你付出了什么努力? –

回答

1

这里是您的解决方案。 首先,它创建arrayobjects代表汽车及其相关值(joinCarPrices)。

,我们还进行排序,使用自定义使用Array#sort功能排序功能priceSort。 根据您要求的算法对汽车进行排序。 最后,我们使用Array#slice只有3个最高价格的汽车。

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); 

和继承人一个JSFiddle显示它的工作!

1

这仅仅是一个可能的解决方案:

//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; 
    }