Sort two arrays the same way

前端 未结 12 2267
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 15:48

For example, if I have these arrays:

var name = [\"Bob\",\"Tom\",\"Larry\"];
var age =  [\"10\", \"20\", \"30\"];

And I use name.sort

12条回答
  •  悲哀的现实
    2020-11-27 16:46

    inspired from @jwatts1980's answer, and @Alexander's answer here I merged both answer's into a quick and dirty solution; The main array is the one to be sorted, the rest just follows its indexes

    NOTE: Not very efficient for very very large arrays

     /* @sort argument is the array that has the values to sort
       @followers argument is an array of arrays which are all same length of 'sort'
       all will be sorted accordingly
       example:
    
       sortMutipleArrays(
             [0, 6, 7, 8, 3, 4, 9], 
             [ ["zr", "sx", "sv", "et", "th", "fr", "nn"], 
               ["zero", "six", "seven", "eight", "three", "four", "nine"] 
             ]
       );
    
      // Will return
    
      {  
         sorted: [0, 3, 4, 6, 7, 8, 9], 
         followed: [
          ["zr", th, "fr", "sx", "sv", "et", "nn"], 
          ["zero", "three", "four", "six", "seven", "eight", "nine"]
         ]
       }
     */
    

    You probably want to change the method signature/return structure, but that should be easy though. I did it this way because I needed it

    var sortMultipleArrays = function (sort, followers) {
      var index = this.getSortedIndex(sort)
        , followed = [];
      followers.unshift(sort);
      followers.forEach(function(arr){
        var _arr = [];
        for(var i = 0; i < arr.length; i++)
          _arr[i] = arr[index[i]];
        followed.push(_arr);
      });
      var result =  {sorted: followed[0]};
      followed.shift();
      result.followed = followed;
      return result;
    };
    
    var getSortedIndex = function (arr) {
      var index = [];
      for (var i = 0; i < arr.length; i++) {
        index.push(i);
      }
      index = index.sort((function(arr){
      /* this will sort ints in descending order, change it based on your needs */
        return function (a, b) {return ((arr[a] > arr[b]) ? -1 : ((arr[a] < arr[b]) ? 1 : 0));
        };
      })(arr));
      return index;
    };
    

提交回复
热议问题