Reputation: 2115
So, I've got a nice array like so:
["Mexico", "Belize", "Canada", "US"]
I want to sort it north-to-south.
I want:
["Canada", "US", "Mexico", "Belize"]
How to do this in javascript?
I have a preset of countries. I can tell Javascript "Hey, that array of countries I just gave you? Sort it Canada, US, Mexico, Belize."
This is for a static graphic, won't have to be dynamic, hard-coding OK.
I've got: my_array.sort() But I have no idea what to do next. Everything online seems to sort by number or alphabet.
And FWIW, list of countries is just an example. In real life, I'm trying to sort sources of government funding: state, federal, trust fund, tobacco settlement. But that's a pretty abstract question. Better to use something concrete like countries, no?
Upvotes: 0
Views: 332
Reputation: 147453
You might create a function that returns the latitude of a country like:
function getLatitude(country) {
var countries = {
Belize : 17.0667,
Canada : 45.4,
Mexico : 19,
US : 38.8833 // Should this be America?
}
return countries[country];
}
however you need to work out what the latitude is—perhaps it's a centroid? Maybe it's from a service that provides the latitude of locations?
Then to sort them:
["Mexico", "Belize", "Canada", "US"].sort(function(a, b) {
return getLatitude(a) - getLatitude(b);
});
// ["Belize", "Mexico", "US", "Canada"]
You need to work out how to handle locations that you can't get a latitude for, should they be removed or sorted to one end or the other?
Upvotes: 2