133

I have an array like this:

arr = []
arr[0] = "ab"
arr[1] = "abcdefgh"
arr[2] = "abcd"

After sorting, the output array should be:

arr[0] = "abcdefgh"
arr[1] = "abcd"
arr[2] = "ab"  

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

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
ramesh kumar
  • 1,615
  • 3
  • 13
  • 18
  • 6
    @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 07 '13 at 16:02

12 Answers12

306

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
});
Salman A
  • 262,204
  • 82
  • 430
  • 521
13

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'));
Community
  • 1
  • 1
Bharata
  • 13,509
  • 6
  • 36
  • 50
4

With modern JavaScript you can do like this:

Descending order

const arr = [
  "ab",
  "abcdefgh",
  "abcd",
  "abcdefghijklm"
];

arr.sort((a, b) => b.length - a.length);

console.log(JSON.stringify(arr, null, 2));

Ascending Order - Just switch the a with b

const arr = [
  "ab",
  "abcdefgh",
  "abcd",
  "abcdefghijklm"
];

arr.sort((a, b) => a.length - b.length);

console.log(JSON.stringify(arr, null, 2));
V. Sambor
  • 12,361
  • 6
  • 46
  • 65
3

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

var arr = ['1234', '12', '12345', '1'];

bubbleSort(arr );

function bubbleSort(a) {
    var swapped;
    do {
        swapped = false;
        for (var i = 0; i < a.length - 1; i++) {
            if (a[i].length < a[i + 1].length) {
                var temp = a[i];
                a[i] = a[i + 1];
                a[i + 1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}

console.log(arr );
node_saini
  • 727
  • 1
  • 6
  • 22
shareef
  • 9,255
  • 13
  • 58
  • 89
1
#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
1

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;
}
User123456
  • 2,492
  • 3
  • 30
  • 44
1
let arr  = [5,2,100,1,20,3];
arr.sort((a,b)=>{
  return a-b 
})

console.log(arr) //[1, 2, 3, 5, 20, 100]

on the return value, the sort method will perform the functionality of swapping of an elements

return < 0  { i.e -ve number then  a comes before b}
return > 0  { i.e +ve number then  b comes before a}
return == 0 { order of a and b remains same }
0

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!

Community
  • 1
  • 1
Nico
  • 4,248
  • 1
  • 20
  • 19
0

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

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

0

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'));
ToVine
  • 560
  • 5
  • 16
Hiền
  • 11
0
let array = [`ab`, `abcdefgh`, `abcd`];
let newArray = array.sort((a,b) => {
    return b.length - a.length
})
console.log(newArray);

Please the following code

Force Bolt
  • 1,117
  • 9
  • 9
-3
<script>
         arr = []
         arr[0] = "ab"
         arr[1] = "abcdefgh"
         arr[2] = "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

Mad Scientist
  • 340
  • 4
  • 14