安排Javascript阵列 [英] Arrange Javascript Arrays
问题描述
我有一系列汽车和一系列与每辆车相对应的价格。
I have array of cars and an array of price corresponding to each car.
我想实现函数highest3,它将按价格(从最高到最低)按顺序返回3辆汽车的数组。
I want to implement the function highest3 which will return an array of 3 cars in order by their price (highest to lowest).
但是,如果价格相等,则按字母顺序返回汽车。
However, if the price is equal, then it returns the cars in alphabetical order.
在这个例子中下面,悍马将是第一个条目。
In this example below, "Hummer" would be the first entry.
代码
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.
}
有人可以帮我实现最高3功能吗?我是新手。谢谢。
Can someone please help me to implement the highest3 function? I am a newbie. Thanks.
推荐答案
这是一个适合您的解决方案。
首先,它创建一个数组
的对象
,它们代表汽车及其相关值( joinCarPrices
)。
Here is a solution for you.
First of all it creates an array
of objects
which represent the cars and their associated values (joinCarPrices
).
然后我们使用自定义排序功能执行排序 priceSort
使用 Array#sort 功能。
根据您要求的算法对汽车进行排序。
最后,我们使用 Array#slice 只有3个最高价格的汽车。
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);
还有一个 JSFiddle 显示它正常工作!
And heres a JSFiddle showing it working!
这篇关于安排Javascript阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!