How to sort by length and then alphabetically
Asked Answered
L

3

15

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!

Libratory answered 14/6, 2017 at 20:24 Comment(0)
B
13

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)
Bikol answered 14/6, 2017 at 20:28 Comment(1)
Also works: return a.length === b.length ? a.localeCompare(b) : a.length - b.lengthNegrete
C
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);
Clack answered 14/6, 2017 at 20:30 Comment(2)
Just a heads up about sort, it changes the source array so you don't need to assign it to a new variable. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Sri
If you don't want to change the original array you can make a copy first like this #9593240Sri
C
0

arr.sort((a, b) => a.length - b.length || this)

Chromogenic answered 30/11, 2023 at 0:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.