I am trying to sort objects by there properties. I have a problem on Opera and IE with my function. Till now, I have debugged the problem on Opera at this stage:
- Open “Opera browser” and press cntr+shift+i. Choose the console.
-
Pass this code in the console and press shift+enter.
var DataArray=["Other","Attitude","Attitude","Delivery/timings","General Performance","Personal Planning","Other"] DataArray=DataArray.sort(function(a,b) { return a<b; }); JSON.stringify(DataArray);
You should get correct result like this:
[“Personal Planning”,”Other”,”Other”,”General Performance”,”Delivery/timings”,”Attitude”,”Attitude”]
-
Now change the sort function in this way a>b like this and press enter+shift to exucute it.
var DataArray=["Other","Attitude","Attitude","Delivery/timings","General Performance","Personal Planning","Other"] DataArray=DataArray.sort(function(a,b) { return a>b; }); JSON.stringify(DataArray);
My result is:
[“Attitude”,”Delivery/timings”,”Attitude”,”General Performance”,”Other”,”Other”,”Personal Planning”]
Note the first, the second and the third value?What is going on?
If you execute this in the console “Attitude”=”Attitude” it returns true…
Any ideas?
Thanks in advance.
EDIT:
And the part with the IE:
CODE:
var DataArray=['Other','Attitude','Attitude','Delivery/timings','General Performance','Personal Planning','Other'];
DataArray=DataArray.sort(function(a,b)
{
return a<b;
});
prompt('',DataArray);
Result(correct):Personal Planning,Other,Other,General Performance,Attitude,Attitude,Delivery/timings
CODE:
var DataArray=[‘Other’,’Attitude’,’Attitude’,’Delivery/timings’,’General Performance’,’Personal Planning’,’Other’];
DataArray=DataArray.sort(function(a,b)
{
return a>b;
});
prompt('',DataArray);
RESULT (incorrect): Attitude,Attitude,Other,Delivery/timings,General Performance,Other,Personal Planning
SOLUTION:
sortableArray=sortableArray.sort(function(a,b)
{
if(a.Category>b.Category)
{
return 1;
}
if(a.Category<b.Category)
{
return -1;
}
return 0;
});
To sort in descending way the data use reverse() function.
Thank you for the help. Especially to @nnnnnn
This isn’t a problem with any particular browser, it is a problem with not having read the
.sort()function documentation. The callback you pass to.sort()is not supposed to return a boolean, it is supposed to return a number that is: