JavaScript sort of Array of arrays

后端 未结 2 461
情歌与酒
情歌与酒 2021-01-26 19:22

I have this array of arrays. I want it to be sorted by arrays\' length. I use array.sort( (a, b) => a.length > b.length) );

[ 
  [],
  [ 2, 2,         


        
2条回答
  •  遇见更好的自我
    2021-01-26 19:57

    To do the sort function, you have to provide the max, min equal (+1 (>0 actually), -1 (<0 actually), 0 (for equals)), the faster way is by substract the results:

    arr.sort(function(a, b){
      // ASC  -> a.length - b.length
      // DESC -> b.length - a.length
      return a.length - b.length ;
    });
    

提交回复
热议问题