javascript - native Array.prototype.sort() 和 _.sortBy() 以不同方式对值进行排序

标签 javascript arrays sorting lodash

我正在尝试根据整数属性对对象数组进行排序。当使用 lodash 的方法 _.sortBy() 时,顺序符合预期,但当我使用内置方法时,它是不正确的。

在此处检查代码段:jsbin link .这不是最易读的例子。我无法弄清楚我编写的排序方法有什么问题。延迟值为 0 的对象应保持其在数组中的原始顺序,但 native 排序方法不会发生这种情况。如果我应该编辑我的示例以更加清晰,请在评论中告诉我。

最佳答案

您的排序方法似乎没有问题。但是,您的期望可能并不完全正确。

_.sortBy() 使用稳定的排序算法。如果它遇到彼此相等的元素(比如你的 0 延迟值),它会按照找到它们的相同顺序留下元素。 http://underscorejs.org/#sortBy

另一方面,

Array.prototype.sort() 的算法不保证稳定。

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

关于javascript - native Array.prototype.sort() 和 _.sortBy() 以不同方式对值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45126469/

相关文章:

javascript - 揭示模块模式 : func. apply(null, arr) 与 func.apply(this, arr) 其中 func 在匿名函数中

c++ - 以随机顺序遍历数组

java - 将 double 值从字符串添加到数组列表

javascript - 幻灯片内的光滑 slider 附加点

javascript - 防止在 ember 应用程序中拖放默认值

javascript - 在 React 中发布数据

java - 数组如何在 Java 内部工作?

python - 对于 Python,如何对固定大小的列表中的元素进行排序和合并

c - time.h 和文件中的算法 C 代码

database - 如何设计可重排序的表?