How to sort an array based on the length of each element?

You can use Array.sort method to sort the array. A sorting function that considers the length of string as the sorting criteria can be used as follows:

arr.sort(function(a, b){
  // ASC  -> a.length - b.length
  // DESC -> b.length - a.length
  return b.length - a.length;
});

Note: sorting ["a", "b", "c"] by length of string is not guaranteed to return ["a", "b", "c"]. According to the specs:

The sort is not necessarily stable (that is, elements that compare
equal do not necessarily remain in their original order).

If the objective is to sort by length then by dictionary order you must specify additional criteria:

["c", "a", "b"].sort(function(a, b) {
  return a.length - b.length || // sort by length, if equal then
         a.localeCompare(b);    // sort by dictionary order
});

Leave a Comment