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

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

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

    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
    });
    
    0 讨论(0)
  • 2020-11-28 23:23
    #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
    
    0 讨论(0)
提交回复
热议问题