Suppose I need to sort arrays of an array in ascending order, where the first element is min, then the second element is min, and so on. Here's how you can achieve this using the sort method:
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);
When dealing with arrays containing more than 3 elements, the solution presented above becomes cumbersome with multiple if statements:
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];
});
But what if the length of the array is unknown or needs to be loaded dynamically? Is there a generic approach that avoids repetitive if conditions? Perhaps recursion or loops can help:
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);
However, running the code gives unexpected results:
[
[
0,
1,
1
],
[
0,
2,
3
],
[
2,
1,
5
],
[
0,
2,
5
]
]
which does not match the desired outcome.