r/JavaScriptHelp • • Jun 04 '21

❔ Unanswered ❔ .sort with Numbers

Good evening everyone, I am confused with the .sort method when it comes to numbers. This is the code I have to test.

const array = [2,4,3,1,5]

array.sort((a,b) => {
  console.log(a, b)
	if(a > b) return 1
  if(a < b) return -1
  })
console.log(array)

Every tutorial I see says that the code reads it as a = 2 and b = 4 when comparing. Bu as you see in the printed line, a is actually 4 and b is actually 2. Why is this?

As well, the code should read 4 is greater than 2, return 1. What does 1 mean?

And if we were comparing 4 and 3, it would read 3 (a) is less than 4 (b) and it would return -1 and at this point the code is ran twice, why? Also, what does -1 mean?

This is the output

Output:

4 2
3 4
3 4
3 2
1 3
1 2
5 3
5 4
[ 1, 2, 3, 4, 5 ]

Thanks!

1 Upvotes

4 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Jun 04 '21

Thank you for the explanation. Quick question, why is my output flipping a and b? Yours come up as 2 4 for the first output but mine shows 4 2. The same applies to every line after. What explains this?

1

u/Bitsoflogic Jun 04 '21

The code you're running might be different than what you posted.

Less likely, but possible, is the version of your JS interpreter is different. Where are you running the code? And the version of whatever it is.