Sort
The sort
method sorts the elements of an array and returns the sorted array. The default sort order is built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
Syntax
arr.sort([compareFunction]);
compareFunction
specifies a function that defines the sort order. If omitted, the aray elements are converted to strings, then sorted according to each character's Unicode code point value
- firstEl - the first element for comparison.
- secondEl - the second element for comparison.
Examples
let days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
days.sort();
console.log(days); // expected output:["Friday", "Monday", "Saturday", "Sunday", "Thursday", "Tuesday", "Wednesday"]
let nums = [5, 1, 9, 20, 3, 26, 7, 18];
nums.sort();
console.log(nums); // expected output: [1, 18, 20, 26, 3, 5, 7, 9]
let nums = [5, 1, 9, 20, 3, 26, 7, 18];
nums.sort( (first, second) => first - second);
console.log(nums); // expected output: [1, 3, 5, 7, 9, 18, 20, 26]
Advanced usage
When we return 1, the function communicates to sort()
that the object b
takes precedence in sorting over the object a
. Returning -1 would do the opposite.
let compare = (a, b) => {
if( a < b ) return -1;
if( a > b ) return 1;
if( a === b ) return 0;
}
[5, 3, 6, 92, 1].sort(compare); // [1, 3, 5, 6, 92]
Usage with ASCII values
let symbolsArr = ['%', '#'];
symbolsArr.sort(); // ['#', '%'] because in ASCII table '#' is before '%'
Compare objects by specific value
let fruitsList = [
{ 'fruits': 'apples', 'kg': 5 },
{ 'fruits': 'bananas', 'kg': 4 },
{ 'fruits': 'kiwis', 'kg': 2 },
];
fruitsList.sort( (fr1, fr2) => {
let comparison = 0;
fr1.kg > fr2.kg ? comparison = 1 : comparison = -1;
return comparison;
})
Compare objects by any value
const users = [
{ id: 1, name: 'Samantha', height: 165 , weight: 52 },
{ id: 2, name: 'Kurtis', height: 184 , weight: 86 },
{ id: 3, name: 'Patricia', height: 173 , weight: 60 },
{ id: 4, name: 'Nicholas', height: 169 , weight: 68 },
];
const compareValues(key, order = 'asc') {
return const innerSort(a, b) {
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
const varA = (typeof a[key] === 'string')
? a[key].toLowerCase() : a[key];
const varB = (typeof b[key] === 'string')
? b[key].toLowerCase() : b[key];
let comparison = 0;
if(varA > varB) comparison = 1;
else if (varA < varB) comparison = -1;
return (
(order === 'desc') ? (comparison * -1) : comparison
)
}
}
let sorted = nodesArr.sort(compareValues('height'));
let sorted = nodesArr.sort(compareValues('weight', 'desc'));
List of Resources
MDN: Array.prototype.sort()
freeCodeCamp: Array.prototype.sort