Sort array alphabetically
JavaScript, Array · Feb 15, 2023

Sorts an array of objects alphabetically based on a given property.
- Use
Array.prototype.sort()
to sort the array based on the given property. - Use
String.prototype.localeCompare()
to compare the values for the given property.
const alphabetical = (arr, getter, order = 'asc') =>
arr.sort(
order === 'desc'
? (a, b) => getter(b).localeCompare(getter(a))
: (a, b) => getter(a).localeCompare(getter(b))
);
const people = [ { name: 'John' }, { name: 'Adam' }, { name: 'Mary' } ];
alphabetical(people, g => g.name);
// [ { name: 'Adam' }, { name: 'John' }, { name: 'Mary' } ]
alphabetical(people, g => g.name, 'desc');
// [ { name: 'Mary' }, { name: 'John' }, { name: 'Adam' } ]
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.