How to sort an array based on the length of each element?
We can use Array.sort method to sort this array.
ES5 solution
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
For ascending sort order:
a.length - b.length
For descending sort order:
b.length - a.length
ES6 solution
Attention: not all browsers can understand ES6 code!
In ES6 we can use an arrow function expressions.
let array = ["ab", "abcdefgh", "abcd"];
array.sort((a, b) => b.length - a.length);
console.log(JSON.stringify(array, null, '\t'));
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
});