Reputation: 5408
I have been debugging my JavaScript code for two days and now I found that it works in Firefox.
I uploaded the code into jsFiddle so you can test it there.
It works perfect in Firefox v23 but it doesn't sort in Chromium v28.0.1500.71. I'm using jQuery v1.10.1
I don't know if the error is on the sort()
function or maybe in the jQuery library.
Should this be reported as a bug in Chromium?
var data = {
"list": [
{
"title": "a",
"date": "03/08/2010"
},
{
"title": "b",
"date": "31/07/2010",
},
{
"title": "c",
"date": "08/08/2010",
},
{
"title": "d",
"date": "01/08/2010"
},
{
"title": "e",
"date": "11/12/2010"
},
{
"title": "f",
"date": "10/12/2010"
},
{
"title": "g",
"date": "12/12/2010"
},
{
"title": "h",
"date": "14/12/2010"
},
{
"title": "i",
"date": "11/12/2010"
},
{
"title": "j",
"date": "05/08/2010"
},
{
"title": "k",
"date": "03/08/2010"
}
]
};
// Sort
$.each(data, function (key, val) {
val.sort(function(a, b) {
return a.title.toLowerCase() > b.title.toLowerCase();
});
// The object is not sorted here
});
// Print
document.querySelector("pre").textContent =
JSON.stringify(data, null, 4);
Upvotes: 1
Views: 1631
Reputation: 318182
Try it like this :
$.each(data, function (key, val) {
val.sort(function(a, b) {
return a.title.toLowerCase().localeCompare(b.title.toLowerCase());
});
});
$("pre").text( JSON.stringify(data, null, 4) );
localeCompare
returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order, in other words it returns -1, 1 or 0, while comparing strings with <
or >
returns true or false, which is not what sort()
is expecting.
Upvotes: 1
Reputation: 887275
Your sort
comparer is broken.
The sort
callback is expected to return a negative number, 0
, or a positive number, depending on whether the first argument is smaller than, equal to, or larger than the second.
You're always returning a boolean, which is not what it's supposed to do.
Upvotes: 3