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

前端 未结 9 1378
傲寒
傲寒 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

    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;
    }
    

提交回复
热议问题