12

Assume I had the following Javascript array. How do you sort by length, then alphabetically?

Assume the following array:

var array = ["a", "aaa", "bb", "bbb", "c"];

When sorted it should produce: a, c, bb, aaa, bbb. Thank you in advance!

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Mike Smith
  • 145
  • 1
  • 8

2 Answers2

11

You can first sort by length and then use localeCompare() to sort alphabetically.

var array = ["a", "aaa", "bb", "bbb", "c"];
array.sort(function(a, b) {
  return a.length - b.length || a.localeCompare(b)
})

console.log(array)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
8

Sort by length first then alphabetically using the || operator for more than one criteria. However, in your case, a simple sort will do.

var array = ["a", "aaa", "bb", "bbb", "c"];

array.sort(function(a, b) {
  return a.length - b.length || a.localeCompare(b);
});

console.log(array);

Or

var array =["c", "aa", "bb", "bbb", "b", "aaa", "a"].sort();

array.sort(function(a, b) {
  return a.length - b.length || 0;
});

console.log(array);
Rick
  • 1,035
  • 10
  • 18
  • Just a heads up about sort, it changes the source array so you don't need to assign it to a new variable. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?v=control – Jason Sperske Jun 14 '17 at 20:34
  • If you don't want to change the original array you can make a copy first like this https://stackoverflow.com/questions/9592740/how-can-you-sort-an-array-without-mutating-the-original-array – Jason Sperske Jun 14 '17 at 20:35