How to sort by length and then alphabetically

Suppose I had the following Javascript array. How to sort by length, then alphabetically. Assume the following array:

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

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

+4
source share
3 answers

You can sort by length first and then use localeCompare()to sort in alphabetical order.

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

console.log(array)
Run codeHide result
+3
source

Sort by length first, then alphabetically using || operator for several criteria. However, in your case there will be a simple view.

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

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

console.log(array);
Run codeHide result

or

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

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

console.log(array);
Run codeHide result
+1
source

Source: https://habr.com/ru/post/1679290/


All Articles