Using Javascript with Underscore.js to Sort the other way

前端 未结 4 838
长情又很酷
长情又很酷 2021-02-01 14:01

I\'m using Javascript sort (with Underscore.js):

_.sortBy([\"Bob\", \"Mary\", \"Alice\"], function (name) {return name})
> [\"Alice\", \"Bob\", \         


        
4条回答
  •  鱼传尺愫
    2021-02-01 14:11

    I would just do what Underscore does under the hood: use the Array#sort method.

    ["Bob", "Mary", "Alice"].sort(function (a, b) {
        if (a < b) return 1;
        if (b < a) return -1;
        return 0;
    });
    

    Or if you don't want the original array modified, clone it first:

    _.clone(["Bob", "Mary", "Alice"]).sort(...)
    

提交回复
热议问题