Sort array of arrays

 avatar
unknown
javascript
3 years ago
2.4 kB
6
Indexable
function sortArray(arrayToSort, First, Second, Third, Fourth) {
  // Sort items by supplier (first), product code (second) and description(third)
  if (isNaN(parseInt(First+Second+Third+Fourth))) { return arrayToSort; }
  arrayToSort.sort(function(x,y){
    var xFirst = x[First].toString().toLowerCase();
    var yFirst = y[First].toString().toLowerCase();
    
    if ((xFirst === yFirst) && (Second !== null)) { // if same first criterion
      var xSecond = x[Second].toString().toLowerCase();
      var ySecond = y[Second].toString().toLowerCase();
      
      if ((xSecond === ySecond) && (Third !== null)) { // if same second Criterion
        var xThird = x[Third].toString().toLowerCase();
        var yThird = y[Third].toString().toLowerCase();
        
        if ((xThird === yThird) && (Fourth !== null)) { // If same last name
          var xFourth = x[Fourth].toString().toLowerCase();
          var yFourth = y[Fourth].toString().toLowerCase();
          return xFourth < yFourth ? -1 : xFourth > yFourth ? 1 : 0; // Sort by fourth criterion
        } 
        return xThird < yThird ? -1 : xThird > yThird ? 1 : 0; // sort by third Criterion
      }
      return xSecond < ySecond ? -1 : xSecond > ySecond ? 1 : 0; // sort by second criterion
    }
    return xFirst < yFirst ? -1 : xFirst > yFirst ? 1 : 0; // sort by first Criterion
  });
  
  return arrayToSort;
}


//// I use it in the following code:

  var arrExport = []; // Create a 2D empty array
  var lenStaff = Number(Object.keys(arrStaff).length); Logger.log(lenStaff);
  for(var i = 0; i < lenStaff; i++){ // Loop through all the staff list to process the data
    if (arrStaff[i][12] === 'Current') { // If status is Current
      
      // Export all data for each Staff
      arrExport.push(["", "", arrStaff[i][1], arrStaff[i][2], arrStaff[i][12], arrStaff[i][13], "", "", "", arrStaff[i][11], "", "", "", "", "", "", "", arrStaff[i][16], "", "", "", "", "", "", "", "", arrStaff[i][4], arrStaff[i][3], "", arrStaff[i][0], arrStaff[i][6], arrStaff[i][7], "", arrStaff[i][9], "", arrStaff[i][10], arrStaff[i][8], "", "", "", "", "", "", arrStaff[i][18], "", "", arrStaff[i][5], arrStaff[i][19], arrStaff[i][20], arrStaff[i][21], arrStaff[i][22], arrStaff[i][23], arrStaff[i][14], arrStaff[i][15]]);
    }
  }
  
  // 3. Sort array by staff surname and first name
  arrExport = sortArray(arrExport, 3, 2, 4, 5);
Editor is loading...