javascript, sort 2 array dependently

后端 未结 6 662
渐次进展
渐次进展 2021-01-04 10:09

for hours i\'ve been trying to figure out how to sort 2 array dependently.

Let\'s say I have 2 arrays.

First one:

array1 = [\'zzzzz\', \'aaaa         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 10:26

    Assumption:

    • The arrays are the same length (this is implied by your question)
    • the contents can be compared with > and < (true in your example, but I wanted to make it clear that it was assumed here)

    So then we can use an insertion sort.

    var value,len = array1.length;
    for (i=0; i < len; i++) {
            value = array1[i];
            for (j=i-1; j > -1 && array1[j] > value; j--) {
                array1[j+1] = array1[j];
                array2[j+1] = array2[j];
            }
    
            items[j+1] = value;
     }
    

提交回复
热议问题