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

前端 未结 9 1377
傲寒
傲寒 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: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!

提交回复
热议问题