Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  8] [ 2]  / answers: 1 / hits: 47525  / 11 Years ago, tue, october 8, 2013, 12:00:00

I have some JSON that is formatted like:



places =[
{
city:Los Angeles,
country:USA,
},
{
city:Boston,
country:USA,
},
{
city:Chicago,
country:USA,
},
]


et cetera...



I am trying to sort this alphabetically BY CITY and am having trouble doing so. I believe the root of my issue seems to be determining the order of the characters (versus numbers). I've tried a simple:



    places.sort(function(a,b) {
return(a.city) - (b.customInfo.city);
});


yet, this subtraction doesnt know what to do. Can someone help me out?


More From » json

 Answers
16

Unfortunately there is no generic compare function in JavaScript to return a suitable value for sort(). I'd write a compareStrings function that uses comparison operators and then use it in the sort function.



function compareStrings(a, b) {
// Assuming you want case-insensitive comparison
a = a.toLowerCase();
b = b.toLowerCase();

return (a < b) ? -1 : (a > b) ? 1 : 0;
}

places.sort(function(a, b) {
return compareStrings(a.city, b.city);
})

[#75136] Monday, October 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hanna

Total Points: 66
Total Questions: 99
Total Answers: 101

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;