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

后端 未结 5 687
遇见更好的自我
遇见更好的自我 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:31

    You can use .sortBy, it will always return an ascending list:

    _.sortBy([2, 3, 1], function(num) {
        return num;
    }); // [1, 2, 3]
    

    But you can use the .reverse method to get it descending:

    var array = _.sortBy([2, 3, 1], function(num) {
        return num;
    });
    
    console.log(array); // [1, 2, 3]
    console.log(array.reverse()); // [3, 2, 1]
    

    Or when dealing with numbers add a negative sign to the return to descend the list:

    _.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
        return -num;
    }); // [3, 2, 1, 0, -1, -2, -3]
    

    Under the hood .sortBy uses the built in .sort([handler]):

    // Default is ascending:
    [2, 3, 1].sort(); // [1, 2, 3]
    
    // But can be descending if you provide a sort handler:
    [2, 3, 1].sort(function(a, b) {
        // a = current item in array
        // b = next item in array
        return b - a;
    });
    

提交回复
热议问题