javascript 函数式无损数组排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30431304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
functional non-destructive array sort
提问by Hurelu
Apart for the native way of cloning an array and then sorting it in place, is there an algorithm and existing implementation that is more suited for non-destructive sorting?
除了克隆数组然后就地排序的本机方式之外,是否有更适合非破坏性排序的算法和现有实现?
Need to sort an array of floats into a new array without changing the source. My search results were rather thin since most of the literature is focused on reducing the memory requirements with in-place sorting.
需要在不更改源的情况下将浮点数组排序为新数组。我的搜索结果相当少,因为大多数文献都专注于通过就地排序来减少内存需求。
Using the native sorted = [].slice().sort()
works fine. This question is about understanding if there are other performant sorting implementations when memory constraints are removed since a new array is needed anyway.
使用本机sorted = [].slice().sort()
工作正常。这个问题是关于了解在删除内存限制时是否还有其他高性能排序实现,因为无论如何都需要一个新数组。
回答by shuaibird
There's a simpler syntax for immutably sorting an array using ES6 spread operator:
使用 ES6 扩展运算符对数组进行不可变排序有一种更简单的语法:
[...array].sort(sortFn)
回答by Sze-Hung Daniel Tsui
As the comments have repeated a few times:
正如评论重复了几次:
shuffledArray.slice().sort()
is the default way to go.- It's not really clear how we could have a better algorithm / method using the libraries your mentioned.
shuffledArray.slice().sort()
是默认的方式。- 目前还不清楚我们如何使用您提到的库获得更好的算法/方法。
Seeing as the motivation for non-destructive sorting is related to writing functional code, and you're looking at Ramda...check out Facebook's ImmutableJS library if you haven't already.
将非破坏性排序的动机视为与编写函数式代码有关,而您正在研究 Ramda……如果您还没有,请查看 Facebook 的 ImmutableJS 库。
Particularly, the Seq
.
You could start storing your array of floats in a Seq
, sort it, and be sure the original Seq remains in the right order.
In addition, it utilizes Lazy evaluation.
http://facebook.github.io/immutable-js/docs/#/Seq
http://facebook.github.io/immutable-js/docs/#/Seq/sortBy
特别是,Seq
. 您可以开始将浮点数组存储在 a 中Seq
,对其进行排序,并确保原始 Seq 保持正确的顺序。此外,它还利用了惰性求值。
http://facebook.github.io/immutable-js/docs/#/Seq
http://facebook.github.io/immutable-js/docs/#/Seq/sortBy