不同浏览器上的javascript排序歧义

标签 javascript arrays sorting browser cross-browser

我得到了相当标准的 JS 数组,类似于:

"entities": [
    {
      "id": "1111",
      "options": {
        "label": "Label",
        "choices": [
          {
            "value": "222222"
          },
          {
            "value": "444444"
          }
        ]
      }
    },
    {
      "id": "2222",
      "options": {
        "label": "Label",
        "choices": [
          {
            "value": "333333"
          },
          {
            "value": "555555"
          }
        ]
      }
    },
...

我的排序函数总是告诉我两个元素是相等的,看起来像这样:

function sortF(a,b){
    return 0;
}

现在我对实体数组进行排序,如下所示:

entities.sort(sortF);

没有变化是我在这里的预期行为,但结果在不同的浏览器上是不同的。例如在 IE 上它很好,但在 Chrome 上它以不同的顺序对数组进行排序。

在 MDN 上,我在排序描述下注意到了这一点,但不确定这是否相关:

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

我怎样才能让它在所有浏览器中都一样工作?如果我的排序函数说两个元素相等,我希望排序函数保持原样。

最佳答案

我建议使用自己的排序属性进行稳定排序:

entities.forEach(function (a, i) {
    a.origin = i;
});


function sortF(a, b){
    return a.origin - b.origin;
}

entities.sort(sortF);

结果,与原数组排序顺序相同的稳定排序

关于不同浏览器上的javascript排序歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079072/

相关文章:

javascript - 如何在 ng-repeat Angularjs 中对对象的内部字段使用 orderBy

javascript - 查找嵌套数组的所有可能组合

Javascript - 从数组中删除元素/对数组中高于特定值的元素求和

python lxml以预定义的顺序写入文件

java - 如何对类的ArrayList进行排序

java - 小程序自动关闭

javascript - Cookie 代码在 Firefox 中失败

java - 多线程数组内容?

c++ - 无法分配功能指针的2D数组

java - 从文本文件读取到字符串数组