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'];

console.log(cities.sort());
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

console.log(nums.sort());
result will be
[10,125,15,20,235,35,355,435,50]
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;
} )
console.log(sortedNum)

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 (a.id > b.id) or (a.name > b.name)//id=num and name=alphabet

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

Discussion (0)