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

前端 未结 9 1388
傲寒
傲寒 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 })

提交回复
热议问题