📖 INDEX
LOADING ENGINE...
JS .sort() Method
Organize arrays like a pro with comparison logic.
🔢
Ready to Sort!
Tutor: The .sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts as strings!
How it works
The sort() method sorts the elements of an array in place. This means the original array is modified.
The Compare Function
To sort numbers or complex objects, you must pass a callback function:
array.sort((a, b) => {
if (a < b) return -1; // a comes first
if (a > b) return 1; // b comes first
return 0; // leave as is
});Glossary
In-place
The method updates the original reference instead of returning a copy.
Lexicographical
Sorting based on alphabetical order/Unicode string values.