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

前端 未结 1 1797
谎友^
谎友^ 2021-01-03 23:59

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.s         


        
相关标签:
1条回答
  • 2021-01-04 00:18

    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;}
    
    0 讨论(0)
提交回复
热议问题