0

Here is the code example which is not working properly in IE 11.

Element with id = END3 should be the last one.

Just don't tell me that I need to write sorting manually. It is not a big deal to implement it, but really?!

var list = [{
    id: "SP1"
  },
  {
    id: "SP4"
  },
  {
    id: "END3"
  },
  {
    id: "SP2"
  }
];

console.log(
  list.sort(function(a, b) {
    if (a.id === "END3") {
      return 1;
    }

    return 0;
  })
);

0

2 Answers 2

1

Your sort comparison function is behaving inconsistently. The function is supposed to return < 0, 0, or > 0, not just 1 or 0. If it's not returning those values, you're giving sort the wrong information to work with, because you tell it any comparison in which a isn't the desired value is equal. It's not guaranteed that END3 will be passed as a at any point, so all comparisons will be "equal", so it's undefined what the result will be really. It's also possible that the inconsistency between SP1, END3 ("equal") and END3, SP1 ("greater") will affect the assumptions of the sorting algorithm.

var list = [{id: "SP1"}, {id: "SP4"}, {id: "END3"}, {id: "SP2"}];


console.log(list.sort(function(a, b) {
  if (a.id === 'END3') {
    return 1;
  } else if (b.id === 'END3') {
    return -1;
  } else {
    return 0;
  }
}));

Sign up to request clarification or add additional context in comments.

4 Comments

from mdn: "compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined."
There are such arrays which will always return 1, or -1 or only 0. Like in case of number comparison and input array [2,2,2,2,2,2], each compare call will return 0.
Yeah, but your return is inconsistent if you pass SP1, END3 (→ equal) or END3, SP1 (→ larger). The correct answer should be "smaller" and "larger" respectively. How that will affect the sort algorithm depends on the implementation details of the algorithm.
I clarified that the likely issue is that END3 is never passed as the a parameter, making all values "equal".
1

Return -1 instead of 0 in the else block. When the compare method returns 0 it leaves a and b unchanged.

var list = [{
    id: "SP1"
  },
  {
    id: "SP4"
  },
  {
    id: "END3"
  },
  {
    id: "SP2"
  }
];

console.log(
  list.sort(function(a, b) {
    if (a.id === "END3") {
      return 1;
    }

    return -1;
  })
);

Docs

2 Comments

Thanks for reply. Anyway the behavior is differs, which one is the correct? IE or Chrome?
@QuestionAndAnswer, Different browser implement different engine, so neither is incorrect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.