javascript, sort 2 array dependently

后端 未结 6 657
渐次进展
渐次进展 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:24

    Using a solution found here to find the new indices after sorting an array, you can apply those indices to array2 like so.

    function sortWithIndices(toSort) {
      for (var i = 0; i < toSort.length; i++) {
        toSort[i] = [toSort[i], i];
      }
      toSort.sort(function(left, right) {
        return left[0] < right[0] ? -1 : 1;
      });
      toSort.sortIndices = [];
      for (var j = 0; j < toSort.length; j++) {
        toSort.sortIndices.push(toSort[j][2]);
        toSort[j] = toSort[j][0];
      }
      return toSort;
    }
    
    
    var array1 = ['zzzz', 'aaaa', 'cccc'];
    var array2 = [3, 7, 1];
    
    // calculate the indices of array1 after sorting. (attached to array1.sortIndices)
    sortWithIndices(array1);
    
    // the final array after applying the sorted indices from array1 to array2
    var final = [];
    
    // apply sorted indices to array2
    for(var i = 0; i < array1.sortIndices.length; i++)
        final[i] = array2[array1.sortIndices[i]];
    
    // output results
    alert(final.join(","));
    

    JSFiddle Demo

提交回复
热议问题