Sorting an Array in JavaScript

To sort arrays in JavaScript, the .sort method is used.

However, numbers are sorted by the first character, that is, 1000 is less than 2; a similar sorting happens in MS Excel

const numbers = [1,67,200, 3, 50, 400]; console.log(numbers); val = numbers.sort(); console.log(val);

Result:

[1, 67, 200, 3, 50, 400]
[1, 200, 3, 400, 50, 67]

To sort by the magnitude of the number, you need to add an argument to sort in the form of a function of two variables

const numbers = [1,67,200, 3, 50, 400]; console.log(numbers); val2 = numbers.sort(function(x,y){     return x - y; }); console.log(val2);

Result:

[1, 67, 200, 3, 50, 400]
[1, 3, 50, 67, 200, 400]

What happens during this sorting:

Two numbers are selected from the array, usually the first and the second initially.

If the function returns a positive value, then the index of the first compared element (the number that is x) in the array increases (it moves to the right).

If the function returns zero, nothing changes.

If the function returns a negative value, then the index of the first compared element (the number that is x) in the array decreases (it moves to the left) while the second one increases.

To see this clearly, let's add some logs

const numbers = [1,67,200, 3, 50, 400]; console.log(numbers); val2 = numbers.sort(function(x,y){ console.log(x,y,x-y); return x - y; }); console.log(val2);

Result:

[1, 67, 200, 3, 50, 400]
67 1 66
200 67 133
3 200 -197
3 67 -64
3 1 2
50 67 -17
50 3 47
400 50 350
400 200 200
[1, 3, 50, 67, 200, 400]

The logs show which numbers are compared.

For clarity, we can sort in descending order

const numbers = [1,67,200, 3, 50, 400]; console.log(numbers); val2 = numbers.sort(function(x,y){ console.log(x,y,y-x); return y - x; }); console.log(val2);

Result:

[1, 67, 200, 3, 50, 400]
67 1 -66
200 67 -133
3 200 197
3 67 64
3 1 -2
50 3 -47
50 67 17
400 50 -350
400 67 -333
400 200 -200
[400, 200, 67, 50, 3, 1]

↓ Articles about JavaScript ↓
Development in JavaScript
Scroll up and down
Find out the screen width
Find out the type of an element
TicTacToe
Errors

Article author: Andrei Olegovich