我正在尝试根据整数属性对对象数组进行排序。当使用 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/