How to sort an array in JavaScript?
Published
How to sort an array of numbers in JavaScript?
const items = [3, 12, 9, 1, -4];
// 🛑 Incorrect as it uses a string comparison
items.sort(); // [ -4, 1, 12, 3, 9 ]
items.sort((a, b) => a - b); // [ -4, 1, 3, 9, 12 ]
How to sort an array of strings in JavaScript?
const items = ["orange", "apple", "pear", "banana"];
items.sort(); // [ 'apple', 'banana', 'orange', 'pear' ]
How to sort an array of objects in JavaScript?
const items = [
{ name: "John" },
{ name: "Rebecca" },
{ name: "Albert" },
{ name: "Berto" },
];
items.sort((a, b) => {
const aName = a.name.toLowerCase();
const bName = b.name.toLowerCase();
if (aName < bName) return -1;
if (aName > bName) return 1;
return 0;
}); // [ { name: 'Albert' }, { name: 'Berto' }, { name: 'John' }, { name: 'Rebecca' } ]
We use the compare function here and get the name from the object and lowercase the string with .toLowerCase()
so that we are comparing consistently cased strings. If we didn’t do this, the sorting would not be accurate as comparing a capitalized string to a lower case string results in a different outcome.
Going further
Have a look at the MDN page on Array.sort
to learn more.
Like this post?
Why don't you let me know on Twitter:
@danawoodman