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's wrong with above code, why it isn't sort? my logic seems fine.
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's wrong with above code, why it isn't sort? my logic seems fine.
Return in the 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>');
You can't use -
operator on strings, they are only for numbers. You need to use <
, >
, <=
or >=
for lexigraphical order.
Nina Scholz's answer is very useful when you work on non-English words, and it works on English words.
Simply changing the -
to >
would make the code 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);