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

前端 未结 9 1337
傲寒
傲寒 2020-11-28 22:31

I have an array like this:

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

After sorting, the output array should be:

相关标签:
9条回答
  • 2020-11-28 23:00

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

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

    0 讨论(0)
  • 2020-11-28 23:03

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

    [the solution of the problem by bubble sort][1]

    [1]: http://jsfiddle.net/sssonline2/vcme3/2/enter code here

    0 讨论(0)
  • 2020-11-28 23:10

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

    0 讨论(0)
  • 2020-11-28 23:12

    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'));
    
    0 讨论(0)
  • 2020-11-28 23:13

    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!

    0 讨论(0)
  • 2020-11-28 23:13

    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;
    }
    
    0 讨论(0)
提交回复
热议问题