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

I have an array like this:

``````arr = []
arr = "ab"
arr = "abcdefgh"
arr = "abcd"
``````

After sorting, the output array should be:

``````arr = "abcdefgh"
arr = "abcd"
arr = "ab"
``````

I want in the `descending` order of the length of each element.

• `sort` is pretty straight forward, where are you having difficulty? – mu is too short May 17 '12 at 6:20
• @muistooshort well default sort() sorts strings alphabeticly, he was looking for the string.length sorting as can be seen in the chosen answer :) – jave.web Aug 7 '13 at 16:02

## 10 Answers

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
});
``````
• I would add that this sorts the array by decreasing length of the items. – davidhq Feb 27 '16 at 20:17
• aha it's in the comment :) didn't see it at first – davidhq Feb 27 '16 at 20:17
• Just to add an information. This snippet won't work for all the cases. – Arunkumar Srisailapathi Apr 10 '16 at 12:42
• Try for arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'l'], it will fail – Arunkumar Srisailapathi Apr 10 '16 at 12:43
• The ES6 way `arr.sort((a, b) => b.length - a.length)` – Fergal Jun 8 '16 at 7:58

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'));``````

Here is the sort, depending on the length of a string with javascript as you asked:

[the solution of the problem by bubble sort]

: http://jsfiddle.net/sssonline2/vcme3/2/`enter code here`

Based on Salman's answer, I've written a small function to encapsulate it:

``````function sortArrayByLength(arr, ascYN) {
arr.sort(function (a, b) {           // sort array by length of text
if (ascYN) return a.length - b.length;              // ASC -> a - b
else return b.length - a.length;                    // DESC -> b - a
});
}
``````

then just call it with

``````sortArrayByLength( myArray, true );
``````

Note that unfortunately, functions can/should not be added to the Array prototype, as explained on this page.

Also, it modified the array passed as a parameter and doesn't return anything. This would force the duplication of the array and wouldn't be great for large arrays. If someone has a better idea, please do comment!

I adapted @shareef's answer to make it concise. I use,

`.sort(function(arg1, arg2) { return arg1.length - arg2.length })`

• this would sort from low length to higher length – Miguel Nov 24 '16 at 16:08
``````#created a sorting function to sort by length of elements of list
def sort_len(a):
num = len(a)
d = {}
i = 0
while i<num:
d[i] = len(a[i])
i += 1
b = list(d.values())
b.sort()
c = []
for i in b:
for j in range(num):
if j in list(d.keys()):
if d[j] == i:
c.append(a[j])
d.pop(j)
return c
``````
• Posting the code alone won't help. Give a brief description of what your code does. – coderpc Apr 23 '20 at 17:10

If you want to preserve the order of the element with the same length as the original array, use bubble sort.

``````Input = ["ab","cdc","abcd","de"];

Output  = ["ab","cd","cdc","abcd"]
``````

Function:

``````function bubbleSort(strArray){
const arrayLength = Object.keys(strArray).length;
var swapp;
var newLen = arrayLength-1;
var sortedStrArrByLenght=strArray;
do {
swapp = false;
for (var i=0; i < newLen; i++)
{
if (sortedStrArrByLenght[i].length > sortedStrArrByLenght[i+1].length)
{
var temp = sortedStrArrByLenght[i];
sortedStrArrByLenght[i] = sortedStrArrByLenght[i+1];
sortedStrArrByLenght[i+1] = temp;
swapp = true;
}
}
newLen--;
} while (swap);
return sortedStrArrByLenght;
}
``````

This code should do the trick:

``````var array = ["ab", "abcdefgh", "abcd"];

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

console.log(JSON.stringify(array, null, '\t'));
``````
``````let array = [`ab`, `abcdefgh`, `abcd`];
let newArray = array.sort((a,b) => {
return b.length - a.length
})
console.log(newArray);
``````

Please the following code

``````<script>
arr = []
arr = "ab"
arr = "abcdefgh"
arr = "sdfds"
arr.sort(function(a,b){
return a.length<b.length
})
document.write(arr)

</script>
``````

The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do

• What is the sorting comparison function supposed to return? Here's a hint: it isn't a boolean. – mu is too short Aug 7 '13 at 17:14
{"ft_lang_label":"__label__en","ft_lang_prob":0.7902771,"math_prob":0.9276081,"size":871,"snap":"2021-21-2021-25","text_gpt3_token_len":214,"char_repetition_ratio":0.13956171,"word_repetition_ratio":0.0,"special_character_ratio":0.2881745,"punctuation_ratio":0.19251336,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9957666,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-06-20T17:13:03Z\",\"WARC-Record-ID\":\"<urn:uuid:f80b003c-477c-4cec-8fc4-46270e49ae9f>\",\"Content-Length\":\"255551\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:1bb86c3f-0b1b-4db4-8e35-1772cc82dade>\",\"WARC-Concurrent-To\":\"<urn:uuid:eeb8cc92-8d38-4cd7-832e-c611a2639437>\",\"WARC-IP-Address\":\"151.101.193.69\",\"WARC-Target-URI\":\"https://stackoverflow.com/questions/10630766/how-to-sort-an-array-based-on-the-length-of-each-element\",\"WARC-Payload-Digest\":\"sha1:F45LXH33ZFTKBPCMLQ2QXT66LRYGT2VU\",\"WARC-Block-Digest\":\"sha1:GET74MROSY4F662LBBKN3NBT4Z4XVS7E\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-25/CC-MAIN-2021-25_segments_1623488249738.50_warc_CC-MAIN-20210620144819-20210620174819-00157.warc.gz\"}"}