JavaScript - method sort();

Hi, everybody - how’re you today?
Can you help me to understand how this fork.

if I use sort for strings everything it’s okay
var myString = [“my string”, “apple” , “baana”, “Bosna i Hercegovina”];
and I use myString.sort(); => and this will be sort by alphabet ok :smiley: - that I udnerstand.

I don’t understand how work this
var myNumbers = [125, 2, 5, 10, 50];
if I use myNumbers.sort(); will be => 10, 125, 2, 5, 50 (by first number)
if I had to do on the _right way _ need to do this myNumbers.sort((a,b) => a-b \or b-a for lower to higher\ ); and that is what I can’t understand
what mean and how work this with (a,b) => a-b

Big thanks :smiley:

One is the default sort order, it orders using the characters Unicode point value
If you specify a function instead you can tell it how to sort, and it is expecting a negative or positive number depending on how you want it to sort things

1 Like

When you pass function as an argument, it executes that function for each element of array.
Then it uses value returned by function to see if this element should be before or after element you compare it with.

In your example you return a-b, where a and b are element being compared. If a is bigger then b, and needs to be after it, a-b will be positive number. Otherwise it will be negative.

So when your function returns positive it will place a after b.

And (a,b)=>a-b is just arrow function that can be written like this for better understanding:

function (a, b) {
  return a - b;
}
1 Like

Can you, please explain me this with some real number 'cus I don’t get it how fun know what is a, what is b ? (if you understand what i don’t understand hah)

Try reading the documentation about sort()