JavaScript - Sort Arrays and Objects
Learn how to sort array and objects with different methods.
Sorting Array
JavaScript Array sort() method
sort() method can be used to sort an array.
By default, sort() method is used to sort string and it will automatically casts array elements to string.
const numbersArray = [0, 1, 8, 5, 50, 10, 80];
numbers.sort();
console.log(numbers);Code result
0, 1, 10, 5, 50, 8, 80
As you notice, sort() orders 10 before 2 because string "10" is before string "2" when comparing first alphabet.
To use sort() method for ordering numbers, we have to pass in a compare function as an argument for sort() method.
JavaScript Array sort() method - with compare function
let numbersArray = [0, 1, 8, 5, 50, 10, 80];
numbersArray.sort(function(a, b) {
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
console.log(numbersArray);
Code result
0, 1, 10, 5, 50, 8, 80
Sorting Object
JavaScript Object sort by key
Sort a JavaScript object using the key.
const countryList = {
SG: {
name: "Singapore"
},
US: {
name: "United States of America"
},
CN: {
name: "Republic of China"
}
}
let unordered = {}
for (const c of Object.keys(countryList)) {
unordered[c] = countryList[c].name
}
const ordered = Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
console.log("unordered", unordered)
console.log("ordered", ordered)unordered {SG:"Singapore",
US:"United States of America",
CN:"Republic of China"}
ordered {CN:"Republic of China",
SG:"Singapore",
US:"United States of America"


