rumburak
rumburak

Reputation: 1137

javascript sort ambiguity on different browsers

I got rather fairly standard JS array, similar to this:

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

I got sorting function that always tells that two elements are equal, that looks like that:

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

Now I sort entities array like:

entities.sort(sortF);

No change is my expected behavior here, but results are different on different browsers. For example on IE it is fine, but on Chrome it sorts the array in different order.

On MDN I noticed this under sort description, but not sure if this is relevant:

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

How can I make this to work the same in all browsers? I want sort function to leave the order as it was if my sort function says that two elements are equal.

Upvotes: 3

Views: 931

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386540

I suggest to make a stable sort with an own property for sorting:

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


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

entities.sort(sortF);

Result, a stable sort with the same sort order as the original array

Upvotes: 3

Related Questions