0

Why nums array is not getting sorted? How does > or < operator works inside sort method as in the below code?

    const nums = [1, 2, 5, 45, 22, 48, 11];
    console.log(nums);      // [1, 2, 5, 45, 22, 48, 11]

    nums.sort((a, b) => a > b);
    console.log(nums);      // [1, 2, 5, 45, 22, 48, 11]
Jens
  • 67,715
  • 15
  • 98
  • 113
Sunil Kumar Das
  • 372
  • 1
  • 2
  • 12
  • For me it looks sorted – Jens Jan 10 '23 at 10:38
  • @Jens — 48 does not come before 11 – Quentin Jan 10 '23 at 10:38
  • 2
    "_How does > or < operator works inside sort_" They don't work in sort method. The method expects a "tri-state" number, that is negative (less than), zero (equal) or positive (greater than). – Teemu Jan 10 '23 at 10:39
  • 1
    the function passed to `sort()` is not expected to return boolean, but a postive/negative or zero number. – TZHX Jan 10 '23 at 10:39
  • @Quentin yes it is in the comment of OP. But not in the output of the code – Jens Jan 10 '23 at 10:39
  • @Jens — It is when I test it. (But the sort algorithm isn't stable) – Quentin Jan 10 '23 at 10:40
  • `return a - b;` will help you – Maik Lowrey Jan 10 '23 at 10:41
  • your snippet is working fine. The second console.log shows `[ 1, 2, 5, 11, 22, 45, 48 ]` – Peterrabbit Jan 10 '23 at 10:43
  • @Teemu #TZHX Apparently the source code I was looking at had it written like that so I was confused. – Sunil Kumar Das Jan 10 '23 at 11:09
  • Well, one of the easiest way to learn how the things work in JavaScript is to [read the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) at MDN, you can't rely on arbitrary code examples found from the internet. – Teemu Jan 10 '23 at 11:26

1 Answers1

1

To compare numbers instead of strings, the compare function can subtract b from a

const nums = [1, 2, 5, 45, 22, 48, 11];
nums.sort((a, b) => a - b);
console.log(nums);
SelVazi
  • 10,028
  • 2
  • 13
  • 29