DEV Community

John Fang
John Fang

Posted on

The tutorial of Array.prototype.sort()

for example

let cities =['Philadelphia','Baltimore','Cleveland','New York','Atlanta','Pittisburth','Boston','Chicago','Milwaukee'];

result of list will follow the first alphabet as ['Atlanta','Baltimore','Boston','Chicago'...]

However, when we get a list of numbers like
let nums = [15,35,20,10,125,355,235,435,50]
and then

result will be
The items inside the result are not follow by the numerical value.

make some changes in the console.log area
let sortedNum = nums.sort( (a,b) => {
if (a > b) return 1; // comparing 15 and 35
else (b > a) return -1; // comparing 35 and 15
return 0;
} )

in this case
[10,15,20,35,50,125,235,355,435]//follow the numerial value

in the function, (a > b) or (b > a)could be replace by anything in the array not just number

like ( > or ( > and name=alphabet

thank you for reading this tutorial of the Array.prototype.sort() method

Discussion (0)