Why is this Array.sort behaviour different in Chrome vs Node.js

拥有回忆 提交于 2020-04-13 16:58:47

问题


Problem

Let's make a basic list and sort it to make sure that 2 is ALWAYS first in the list. Simple enough, right?

[1, 2, 3].sort((a, b) => {
  if (a === 2) return -1;
  return 0;    
});

Chrome result: ✓

[2, 1, 3]

Node result: X

[1, 2, 3]

In order to get this behaviour in Node, you could - weirdly enough - look at the b parameter and make it return 1 if it's 2:

[1, 2, 3].sort((a, b) => {
  if (b === 2) return 1;
  return 0;    
});

With this implementation you get the opposite result; Chrome will be [1, 2, 3] and Node will be [2, 1, 3].

Questions

Do you have a logical explaination for this behaviour? Is my sorting function conceptually flawed? If so, how would you write this sorting behaviour?


回答1:


Do you have a logical explaination for this behaviour?

Browsers use different sorting methods. Therefore they possibly call the provided callback with different arguments in a different order. If your sort function is not consistent, the sorting won't be stable. This will lead to a wrong sort order (it also always would with different input arrays, so your sorting will never really work).

If so, how would you write this sorting behaviour?

Make sure that these two conditions apply to every possible input:

1) Two equal elements should not be sorted:

  sort(a, a) === 0

2) If the sort function gets called in inversed order, the result is also inversed:

  sort(a, b) - sort(b, a) === 0

In your case, both are not fullfilled:

  sort(2, 2) // 1 -> wrong!
  sort(2, 3) - sort(3, 2) // 1 -> wrong!

To write a stable sort, you have to look at a and b:

  function(a, b) {
    if(a === 2 && b === 2)
      return 0;
    if(a === 2)
      return 1;
    if(b === 2)
      return -1;
    return 0;
  }

Or to make that shorter:

  (a, b) => (a === 2) - (b === 2)


来源:https://stackoverflow.com/questions/55995255/why-is-this-array-sort-behaviour-different-in-chrome-vs-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!