How can I do an asc and desc sort using underscore.js?

后端 未结 5 684
遇见更好的自我
遇见更好的自我 2020-12-02 06:55

I am currently using underscorejs for sort my json sorting. Now I have asked to do an ascending and descending sorting using underscore.js. I do no

5条回答
  •  臣服心动
    2020-12-02 07:13

    Descending order using underscore can be done by multiplying the return value by -1.

    //Ascending Order:
    _.sortBy([2, 3, 1], function(num){
        return num;
    }); // [1, 2, 3]
    
    
    //Descending Order:
    _.sortBy([2, 3, 1], function(num){
        return num * -1;
    }); // [3, 2, 1]
    

    If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

    //Descending Order Strings:
    _.sortBy(['a', 'b', 'c'], function(s){ 
        return s.charCodeAt() * -1;
    });
    

提交回复
热议问题