结合使用Javascript和Underscore.js进行其他排序 [英] Using Javascript with Underscore.js to Sort the other way

查看:108
本文介绍了结合使用Javascript和Underscore.js进行其他排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Javascript sort(与Underscore.js结合使用):

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

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

我希望数组以其他方式返回.我该怎么办?

I would like the array to return the other way. How do I do that?

[玛丽",鲍勃",爱丽丝"]

["Mary", "Bob", "Alice"]

我不想在对它进行排序后将其撤消-我希望它在第一次出现时以另一种方式创建.

I don't want to reverse it after it's sorted - I want it to be created the other way around the first time.

谢谢.

推荐答案

我只想做Underscore要做的事情:使用

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(...)

这篇关于结合使用Javascript和Underscore.js进行其他排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆