0

I have an array arr of four number arrays such as:

arr = [
    [4, 1, 3, 2, 0],
    [4, 2, 1, 3, 0],
    [0, 2, 3, 1, 4],
    [0, 3, 1, 2, 4]
]

and I need to sort it to get:

arr = [
    [0, 2, 3, 1, 4],
    [0, 3, 1, 2, 4]
    [4, 1, 3, 2, 0],
    [4, 2, 1, 3, 0],
]

The number arrays can be larger, but the four arrays have always the same size. Sometimes it's necessary to compare more than the first and second elements of the number arrays to get the smaller. I found the code below in this answer, but it is limited to the first two number array elements.

myArray=myArray.sort(function(a,b){
    retVal=0;
    if(a[0]!=b[0]) retVal=a[0]>b[0]?1:-1;
    else if(a[1]!=b[1]) retVal=a[1]>b[1]?1:-1;
    else if(a[2]!=b[2]) retVal=a[2]>b[2]?1:-1;
    return retVal
});

EDIT

In the output, the elements arr[0][0] and arr[1][0] are equal and smaller than the elements arr[2][0] and arr[3][0]. In a second level, the element arr[0][1] is smaller than arr[1][1]. In some cases there are many levels and I can't predict how much.

How could I implement it?

Community
  • 1
  • 1
msampaio
  • 3,394
  • 6
  • 33
  • 53
  • How is the second array (output) sorted? What is the rule? – Mukesh Soni May 21 '17 at 13:03
  • In the output, in a first level, the `arr[0][0]` and `arr[1][0]` are lower than `arr[2][0]` and `arr[3][0]`. In a second level, the `arr[0][0]` is lower than `arr[1][0]`. I will explain in the question. – msampaio May 21 '17 at 13:12

2 Answers2

2

Iterate the arrays until you find elements that don't match and return difference of first mismatch

var arr = [
    [4, 1, 3, 2, 0],
    [4, 2, 1, 3, 0],
    [0, 2, 3, 1, 4],
    [0, 3, 1, 2, 4]
]


arr.sort(function(a,b){       
   for(var i=0; i< a.length; i++){
     // if they don't match, return difference
     if(a[i] !== b[i]){
       return a[i] - b[i];
     }
   }  
   // if we get this far they are the same     
   return 0;
})

console.log(JSON.stringify(arr))
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1
arr.sort(function(a,b) {
      for (i = 0; i < a.length); i++) {
           if (a[i] < b[i])
                return -1;
           if (a[i] > b[i])
                return 1;
       }
       return 0;
  });
nucleon
  • 1,128
  • 1
  • 6
  • 19