Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't Safari 5 sort an array of objects?

Anyone know why Safari 5 (Windows 7) can't sort arrays of objects?

var arr = [{a:1},{a:3},{a:2}];
console.log(arr[0].a+','+arr[1].a+','+arr[2].a);
arr.sort(function(a,b){return a.a > b.a;});
console.log(arr[0].a+','+arr[1].a+','+arr[2].a);

The console result should be

1,3,2
1,2,3

This works fine in FF and IE but Safari returns:

1,3,2
1,3,2
like image 441
Marc Avatar asked Nov 28 '10 21:11

Marc


People also ask

Can we sort array of objects?

To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.


1 Answers

Your comparison function is wrong:

function(a,b){return a.a > b.a;}

The function is expected to return negative, zero or positive depending on whether a < b, a = b or a > b. Your function returns a boolean indicating whether a > b. Try something like:

function(a,b){return a.a - b.a;}
like image 93
casablanca Avatar answered Oct 05 '22 22:10

casablanca