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?
arr[0][0]
andarr[1][0]
are lower thanarr[2][0]
andarr[3][0]
. In a second level, thearr[0][0]
is lower thanarr[1][0]
. I will explain in the question.