Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort by length and then alphabetically

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!

like image 307
Mike Smith Avatar asked Jun 14 '17 20:06

Mike Smith


People also ask

How do you sort by alphabetically and length in python?

Use the Python List sort() method to sort a list in place. The sort() method sorts the string elements in alphabetical order and sorts the numeric elements from smallest to largest. Use the sort(reverse=True) to reverse the default sort order.

How do you sort a list by string length?

For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest. The sort calls len() for each string to get the list of proxy length values, and then sorts with those proxy values.

WHAT IS A to Z sorting?

In general terms, Ascending means smallest to largest, 0 to 9, and/or A to Z and Descending means largest to smallest, 9 to 0, and/or Z to A. Ascending order means the smallest or first or earliest in the order will appear at the top of the list: For numbers or amounts, the sort is smallest to largest.

How do you order a string in alphabetical order?

Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.


1 Answers

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)
like image 193
Nenad Vracar Avatar answered Nov 04 '22 02:11

Nenad Vracar