Why isn't .sort() working as expected?


#1

Question

Why isn’t .sort() working as expected?

Answer

When we use .sort(), if we do not specify a function that defines the sort order, each element of the array will be converted to a string then sorted in ascending order based on each character’s Unicode point value.
For example:

const myArr = [400, 100000, 560];

console.log(myArr.sort())//logs [ 100000, 400, 560 ] to the console because each number is converted to a string then sorted in ascending order based on Unicode code point value

To solve this issue we’ll want to pass .sort() a function that defines the sort order:

const myArr = [400, 100000, 560];

const checkNumbers = (num1, num2) => num1 - num2;

console.log(myArr.sort(checkNumbers));//logs [ 400, 560, 100000 ] to the console