Home > Enterprise >  How to sort arrays of array, sort by first then by second then by third then by ...n th element, in
How to sort arrays of array, sort by first then by second then by third then by ...n th element, in

Time:08-26

For example, if I want to sort arrays of an array, which the first element is min, then the second element is min, then the third... I can use sort to do it:

Array with 2 elements

const arrayOfArray=[[2,1],[0,2],[1,3],[0,4]];
arrayOfArray.sort(function(a,b){
  if(a[0]!=b[0]){
    return a[0]-b[0];
  }
  return a[1]-b[1];
});
console.log(arrayOfArray);

Array with 3 elements:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];
for(let i=0;i<arrayOfArray[0].length;i  ){
    arrayOfArray.sort(function(a,b){
      if(a[0]!=b[0]){
        return a[0]-b[0];
      }
      if(a[1]!=b[1]){
        return a[1]-b[1];
      }
      return a[2]-b[2];
    });
}
console.log(arrayOfArray);
    

How about array with 3,4,5,...n elements? I think this solution is not good enough because it needs to copy and paste if...!=... many times when the array has many elements:

arrayOfArray.sort(function(a,b){
  if(a[0]!=b[0]){
    return a[0]-b[0];
  }
  if(a[1]!=b[1]){
    return a[1]-b[1];
  }
  .
  .
  .
  if(a[n-1]!=b[n-1]){
    return a[n-1]-b[n-1];
  }
  return a[n]-b[n];
});

And what if I don't know the length of the array (eg: need to load it in dynamic way)? Is there generic way to do it? eg: recursion, for loop? I tried:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];
for(let i=0;i<arrayOfArray[0].length;i  ){
    arrayOfArray.sort(function(a,b){
      return a[i]-b[i];
    });
}
console.log(arrayOfArray);

but the output is:

[
  [
    0,
    1,
    1
  ],
  [
    0,
    2,
    3
  ],
  [
    2,
    1,
    5
  ],
  [
    0,
    2,
    5
  ]
]

which is not my desired result.

CodePudding user response:

You can achieve the result you want for arbitrary length arrays by iterating the comparison over all the elements of the inputs to the sort function, returning the difference if there is one, and 0 if all elements of both arrays are equal:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];

arrayOfArray.sort(function (a,b) {
  for (let i = 0; i < a.length; i  ){
    if (a[i] != b[i]) {
        return a[i] - b[i];
    }
  }
  return 0;
});

console.log(arrayOfArray);

CodePudding user response:

It's not universal solution, but in this particular case you can use string comparison:

const arrayOfArray=[[2,1,5],[0,2,5],[0,2,3],[0,1,1]];

const result = arrayOfArray.sort((a, b) => a.join('').localeCompare(b.join('')));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

  • Related