我正在使用 Javascript sort
(使用 Underscore.js):
_.sortBy(["Bob", "Mary", "Alice"], function (name) {return name})
> ["Alice", "Bob", "Mary"]
我希望数组以另一种方式返回。我该怎么做?
[“玛丽”、“鲍勃”、“爱丽丝”]
我不想在排序后将其反转 - 我希望第一次以相反的方式创建它。
谢谢。
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.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我宁愿将它与
Array.reverse
充分利用两者的优势。Instead of throwing underscorejs away, I'd rather use it together with
Array.reverse
to utilize the best of both.我只想做 Underscore 在幕后所做的事情:使用 Array#sort< /a> 方法。
或者,如果您不想修改原始数组,请先克隆它:
I would just do what Underscore does under the hood: use the Array#sort method.
Or if you don't want the original array modified, clone it first:
显然你不应该这样做,因为排序然后反转结果更有意义,但是如果你真的想在排序函数中以相反的顺序排序,你可以这样做......
也值得注意到下划线与本机 JavaScript 排序略有不同,后者在一致排序顺序方面存在一个小的跨平台问题......
Underscore 的
.sortBy
文档指出:它不是返回
0
为了保持项目有序,它返回左侧的索引减去右侧的索引。Obviously you should not do this, as it makes far more sense to sort, then reverse the results, but if you really want to sort in reverse order inside the sort function, you could do something like this...
... also worth noting that underscore is subtly different than native javascript sort which has a small cross platform issue regarding consistent sort order...
Underscore's
.sortBy
documentation states:Which it does by instead of returning
0
to keep items in order, it returns the index of the left side minus the index of the right side.您可以在 ES6 中使用 1 行来完成此操作,只需根据您想要的方向更改
>
即可。.sort()
从 IE6 开始就被支持,你只需传递一个返回 1 或 -1 的函数即可;You can do this with a 1 liner in ES6, just change the
>
depending on the direction you want..sort()
is supported since IE6 and you just pass a function which returns 1 or -1;