Sort array alphabetically

JavaScript, Array · Feb 15, 2023

Sorts an array of objects alphabetically based on a 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.

More like this

  • Order array of objects based on property order

    Sorts an array of objects, ordered by a property, based on the array of orders provided.

    JavaScript, Array · Oct 21, 2020

  • Count grouped elements

    Groups the elements of an array based on the given function and returns the count of elements in each group.

    JavaScript, Array · Nov 3, 2020

  • Group array elements

    Groups the elements of an array based on the given function.

    JavaScript, Array · Oct 22, 2020