Difference between sort(), sort(function(a,b){return a-b;}); and sort(function(a,b){…})

后端 未结 4 596
醉梦人生
醉梦人生 2021-02-02 03:12

I am trying to understand how exactly sort() works and how I am supposed to use it.

I did some research (google) and went through the similar questions here on stackover

4条回答
  •  走了就别回头了
    2021-02-02 03:43

    I think, you would like to combine the sort criteria, like this example which sort by name forst and then by number. Please watch 'John'.

    var myArr = [{ "sortnumber": 9, "name": "Bob" }, { "sortnumber": 5, "name": "Alice" }, { "sortnumber": 4, "name": "John" }, { "sortnumber": 3, "name": "James" }, { "sortnumber": 7, "name": "Peter" }, { "sortnumber": 6, "name": "Doug" }, { "sortnumber": 2, "name": "Stacey" }, { "sortnumber": 14, "name": "John" }, { "sortnumber": 12, "name": "John" }];
    
    myArr.sort(function (a, b) {
        return a.name.localeCompare(b.name) ||  a.sortnumber - b.sortnumber;
    });
    
    console.log(myArr);

提交回复
热议问题