问题描述:

I have an array:

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"

}];

And would like to sort it based on the following order

cities = ['New York', 'Dallas', 'Bevery Hills']

What's the best way to achieve it?

网友答案:

Notice that sort method do sorting in place, so homes is gonna change.

homes.sort(function (a,b){
  return cities.indexOf(a.city) - cities.indexOf(b.city)
});
网友答案:

Since you can use indexOf on cities to look up the final index of any home object, you can do it more efficiently than Array.prototype.sort:

var sortedHomes = new Array(cities.length);

homes.forEach(function (home) {
    var sortedIndex = cities.indexOf(home.city);
    sortedHomes[sortedIndex] = home;
});

(This is still O(n²). You can make it O(n) by flipping cities into a hashmap, but only if you’ve measured that optimization to be worth it.)

If multiple homes can share the same city and cities doesn’t contain duplicate entries (seems the most likely situation if this is the case), you can group the homes by city and combine the result as specified by cities:

var homesByCity = {};

homes.forEach(function (home) {
    var cityHomes = homesByCity[home.city];

    if (cityHomes) {
        cityHomes.push(home);
    } else {
        cityHomes = homesByCity[home.city] = [home];
    }
});

var sortedHomes = cities.reduce(function (sortedHomes, city) {
    return sortedHomes.concat(homesByCity[city] || []);
}, []);

(The approach is O(n) even if the implementation isn’t necessarily.)

网友答案:

I would suggest some functional programming to solve this. The snippet below should get you the result you are looking for.

var sorted = cities.map(function(city) {
    return homes.filter(function(home) {
        return home.city === city;
    });
});

First, map over the cities array to create a new array based on it. Second, for each city, find the corresponding item in the homes array and add that to the correct position in the sorted array.

相关阅读:
Top