How to sort an array alphabetically

adamlacombe

Adam LaCombe

Posted on October 24, 2020

How to sort an array alphabetically

String.localeCompare()

If you're working with a relatively small array, you could use localeCompare().

const arr = [
  {
    name: "Orange"
  },
  {
    name: "Banana"
  },
  {
    name: "Carrot"
  },
  {
    name: "Apple"
  }
];

// [{"name":"Apple"},{"name":"Banana"},{"name":"Carrot"},{"name":"Orange"}]
console.log(arr.sort((a, b) => a.name.localeCompare(b.name)));
Enter fullscreen mode Exit fullscreen mode

Intl.Collator()

If you're working with a large array, I would recommend using Intl.Collator() for performance reasons.

const arr = [
  {
    name: "Orange"
  },
  {
    name: "Banana"
  },
  {
    name: "Carrot"
  },
  {
    name: "Apple"
  }
];
const collator = new Intl.Collator();

// [{"name":"Apple"},{"name":"Banana"},{"name":"Carrot"},{"name":"Orange"}]
console.log(arr.sort((a, b) => collator.compare(a.name, b.name)));
Enter fullscreen mode Exit fullscreen mode

Benchmarks

1,000 strings

Here is a benchmark where we're sorting an array of 1,000 strings. As you can see, Intl.Collator() is 25% faster than localeCompare().

Benchmark 1,000 strings

25 strings

Here is a benchmark where we're sorting an array of only 25 strings. In this case, localeCompare() is 13% faster than Intl.Collator().

Benchmark 25 strings

💖 💪 🙅 🚩
adamlacombe
Adam LaCombe

Posted on October 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related