简体   繁体   中英

Native Array.prototype.sort() and _.sortBy() sorts values differently

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 comments if I should edit my example for more clarity.

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.org/#sortBy

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

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 (eg Mozilla versions dating back to at least 2003) respect this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM