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!
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!
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)
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);
© 2022 - 2025 — McMap. All rights reserved.
return a.length === b.length ? a.localeCompare(b) : a.length - b.length
– Negrete