Files
30-seconds-of-code/snippets/alphabetical.md
Angelos Chalaris a4874b6b68 Add 7 new snippets
2023-01-01 23:16:49 +02:00

882 B

title, tags, author, cover, firstSeen
title tags author cover firstSeen
Sort array alphabetically array chalarangelo blog_images/boutique-home-office-1.jpg 2023-02-15T05:00:00-04:00

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' } ]