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
1 Answer
Reset to default 8There 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条)