简体   繁体   中英

what's the 'sort' method's difference between chrome environment and node environment

I found the sort method shows different behavior between in Chrome environment and in the node environment

const arr = ['l', 'h', 'z', 'b', 's'];
arr.sort((pre, next) => {
    return pre < next;
});
console.log(arr);

the node environment's result is [ 'z', 's', 'l', 'h', 'b' ] , it's sorted.
the chrome console environment's result is ['l', 'h', 'z', 'b', 's'] , nothing changed.
chrome's result is what I expect, I don't understand why it working in node environment.

chrome version is 74.0.3729.169 X64
node vsrions is v10.12.0 .

V8 developer here.

As some of the comments are getting at, this is not about Chrome vs. Node (which should behave the same way). It's due to a difference in V8 versions, where Chrome 74 already has the new behavior whereas Node 10 still has the old. Update to Node 11 and you'll see that same behavior there.

In the past, V8 used a combination of QuickSort (for larger arrays) and InsertionSort (for small arrays, up to 10 elements). InsertionSort just so happens to work correctly with the bad comparator function. Use a test array with 11 elements or more, and it will no longer sort correctly in Node 10.

(Versions of V8 since 7.4 now use TimSort for Array.prototype.sort .)


I know that that's not what this question is about, but for the record and/or anyone else reading this in the future: (pre, next) => pre <= next is not a good comparator function! In JavaScript, Array.prototype.sort expects a comparator that returns a number less than zero, equal to zero, or greater than zero, depending on whether the first argument is less than, equal to, or greater than the second. So the proper way to sort strings is something like:

my_string_array.sort((a, b) => {
  if (a < b) return -1;
  if (a > b) return 1;
  return 0;
});

When you use such a comparator, you will always get the right result, in all versions of Chrome and Node.

When you use a comparator that uses a single comparison and hence returns a boolean value, then true silently maps to 1 and false maps to 0, but that means it accidentally returns "equal" for a bunch of pairs that are not, in fact, equal, which can lead to quite surprising sorting results, especially when the engine uses an unstable sorting algorithm under the hood.

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