amb*_*bar 3 javascript arrays sorting
我有一个数组:
var homes = [{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
}, {
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
}, {
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}];
Run Code Online (Sandbox Code Playgroud)
并希望根据以下顺序对其进行排序
cities = ['New York', 'Dallas', 'Bevery Hills']
Run Code Online (Sandbox Code Playgroud)
实现它的最佳方法是什么?
请注意,Array.prototype.sort()方法在适当的位置进行排序,因此sort会发生变化.
homes.sort(function (a,b){
return cities.indexOf(a.city) - cities.indexOf(b.city)
});
Run Code Online (Sandbox Code Playgroud)