3

I was trying to sort an Array And i got this different behavior in Chrome V79 than Firefox Dev Edition V72 (both in Desktop version).

This was the test,

console.log([4, 2, 5, 1, 3].sort((a, b) => a>b));
console.log(Array.prototype.sort.call([4, 2, 5, 1, 3], (a, b) => a>b));

In Firefox Dev, I get this result,

Firefox Test Result

But In Chrome, Why I get this result,

1st Chrome Test Result

But When I i Pass the same array with var, I get this,

2nd Chrome Test Result

But Yeah it sorts the Array and REWRITES THE VARIABLE but returns the unsorted version of the Array. So, When I am passing The Array directly without any var, i get no sorting. But,

As per MDN's reference page shouldn't it return the sorted Array ??

Why there's difference ??

Note: In the Example Imgs, there are two exmaple's I was practicing call func. And forgot to remove it. So, just ignore it. Both of 'em are same.

7
  • 7
    As it says in the link you posted, you need to return a number. You are supposed to return 0, 1, or -1 from the sort function, not a boolean. Commented Jan 16, 2020 at 15:54
  • 4
    you may read why a boolean return value is a bad idea ... stackoverflow.com/questions/24080785/… Commented Jan 16, 2020 at 15:56
  • 2
    I think .sort((a,b) => a-b); is the cleanest way to sort array ascending. Commented Jan 16, 2020 at 16:00
  • 2
    @AnonymousUser264 the particulars of how .sort() should be implemented are not part of the spec. Chrome and Firefox have slightly different algorithms. Commented Jan 16, 2020 at 16:00
  • 2
    Boolean values can be coerced into numbers, but if they are, true = 1 and false = 0. The problem is that for a sorting callback, returning 0 means "these values are equal". Until very recently (as in, the standards introduced last year), there was no guarantee that the implementation of Array.sort was stable -- that is, there was no guarantee that equal values would retain their relative positions. Thus, returning false/0 when a < b might "happen" to work for stable sort and not for unstable sort or vice-versa, but it's not guaranteed. Commented Jan 16, 2020 at 16:03

1 Answer 1

2

As pointed out in the comments, the function you provide for sorting should return:

  • A positive number if a is greater than b
  • A negative number if b is greater than a
  • 0 if they are equal

Therefore, a simple expression you could return is a - b instead of a > b (if you want to sort ascendingly):

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.