0

I have trouble figuring out how the Edge browser is comparing values in javascript. I was sorting an array and my code works fine in Firefox but not in Edge. Here is an example from the MDN page:

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);

When you paste this in the Edge console, the result is (5) [1, 2, 3, 4, 5], as expected.

But if you use > instead of - (my goal is to compare strings), then...

let numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a > b);
console.log(numbers);
(5) [4, 2, 5, 1, 3]

The sorting is not working. So I guess this is because sort is waiting for an integer and not a boolean. (Note that the code above is working fine in Firefox).

Now, my problem is that I want to compare strings. My code looks like this:

results = elems.sort((a, b) => {
  return getPropertyOrEmptyString(a, propName) > getPropertyOrEmptyString(b, propName);
});

This code is sorting fine in Firefox but not in Edge, once again probably because sort() wants an integer not a boolean, but how can I compare string then? I mean, if I write ["b", "a"].sort() in Edge it works, so it can compare them... I guess I should use an Intl.Collator but that seems complicated for a simple string comparison...

Fla
  • 536
  • 6
  • 23

0 Answers0