javascript - Native Array.prototype.sort() and _.sortBy() sorts values differently - Stack Overflow

I am trying to sort array of objects based on an integer property. When using lodash's method _.so

I am trying to sort array of objects based on an integer property. When using lodash's method _.sortBy() the order is as expected but when I use the built in method it isn't right.

Check the snippet here: jsbin link. It's not the most readable example. I am not able to figure what is wrong with the sort method that I have written. The objects which have delay value 0 should maintain their original order in the array but that's not happening with the native sort method. Let me know in ments if I should edit my example for more clarity.

I am trying to sort array of objects based on an integer property. When using lodash's method _.sortBy() the order is as expected but when I use the built in method it isn't right.

Check the snippet here: jsbin link. It's not the most readable example. I am not able to figure what is wrong with the sort method that I have written. The objects which have delay value 0 should maintain their original order in the array but that's not happening with the native sort method. Let me know in ments if I should edit my example for more clarity.

Share Improve this question edited Jul 16, 2017 at 14:54 Benny Johansson 7716 silver badges18 bronze badges asked Jul 16, 2017 at 8:16 nandwana92nandwana92 1052 silver badges11 bronze badges 1
  • I don't undestand your example (try posting a better one), but in general, built-in sort is not guaranteed to be stable (that is, equal objects don't necessary retain their original relative positions). – georg Commented Jul 16, 2017 at 8:32
Add a ment  | 

1 Answer 1

Reset to default 8

There seems to be nothing wrong with your sort method. However, your expectations might not be entirely correct.

_.sortBy() uses a stable sorting algorithm. If it encounters elements that are equal to each other (like your 0 delay values) it leaves the elements in the same order it found them. http://underscorejs/#sortBy

Array.prototype.sort()'s algorithm on the other hand is not guaranteed to be stable.

If pareFunction(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/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744386477a4571688.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信