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?

2
  • How is the second array (output) sorted? What is the rule? Commented May 21, 2017 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
    Commented May 21, 2017 at 13:12

2 Answers 2

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))

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;
  });
1
  • length() is not a function
    – charlietfl
    Commented May 21, 2017 at 13:22

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.