JavaScript: alphabetize and sort by number


This post goes over how to alphabetize and sort by number with JavaScript.

Problem

Given an array of objects:

const objects = [
  {
    number: 2,
    string: 'Two-B',
  },
  {
    number: 2,
    string: 'Two-A',
  },
  {
    number: 1,
    string: 'One',
  },
];

How does one alphabetize by property string and sort by property number?

Solution

To alphabetize by property string:

objects.sort((a, b) => a.string.localeCompare(b.string));

To sort by property number:

objects.sort((a, b) => a.number - b.number);

Output:

[
  { number: 1, string: 'One' },
  { number: 2, string: 'Two-A' },
  { number: 2, string: 'Two-B' },
];

Since Array.prototype.sort() mutates the array, create a copy of the array with slice:

const copy = objects.slice();

Or by spread:

const copy = [...objects];

Demo

Replit:



Please support this site and join our Discord!