Object sorting doesn't work?

var city = [{
"city":"London"
},{
"city":"Wales"
}
,{
"city":"Atom"
}
,{
"city":"Bacelona"
}];

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

console.log(city)

Not sure what is wrong with the code above, why is it not sorting? my logic seems beautiful.

+4
source share
2 answers

Return to function for strings:

return a.city.localeCompare(b.city);

var city = [{ "city": "London" }, { "city": "Wales" }, { "city": "Atom" }, { "city": "Bacelona" }];

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

document.write('<pre>' + JSON.stringify(city, 0, 4) + '</pre>');
Run codeHide result
+2
source

You cannot use the operator -for strings; they are only for numbers. For leksigraficheskogo order you need to use <, >, <=or >=.

Nina Scholz's answer is very useful when you work on non-English words, and he works on English words.

A simple change -to >will cause the code to work:

var city = [{
    "city": "London"
}, {
    "city": "Wales"
}, {
    "city": "Atom"
}, {
    "city": "Bacelona"
}];

city.sort(function(a,b){
    return (a.city > b.city ? 1 : (a.city === b.city ? 0 : -1));
});

console.log(city);
+2
source

All Articles