Reputation: 71
I need to see if this type of array is sorted:
var grilla = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
I know how to show all of the elements and how to see if a simple array is sorted, but no clue on how to do this. My "solution" doesn't cover cases like [ [1, 2, 3], [4, 5, 6], [8, 7, 9] ] where the complete array of arrays is unsorted because of the last array, but I don't know how to reach the last array to check if it's sorted.
function chequearSiGano() {
for(var i=0;i<(grilla.length-1);i++) {
if (grilla[i][grilla.length-1] > grilla[i+1][0]) {
return false;
}
for(var j=0;j<(grilla.length-1);j++) {
if (grilla[i][j] > grilla[i][j+1]) {
return false;
}
}
}
return true;
}
Upvotes: 7
Views: 633
Reputation: 1333
You can use .flat() function that converts nested array into flat array and check it as simple array: e.g.:
const grill = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const flattedArray = grill.flat()
function chequearSiGano() {
for(let i=0;i<(flattedArray .length-1);i++) {
if (flattedArray[i] > flattedArray[i+1]) {
return false;
}
}
return true;
}
Upvotes: 1
Reputation: 1
To make it easy, flatten the array
Then you can either use the code you use for a flat array or you can even go like the following
const checkIfSorted = array => {
var flat = array.flat();
var flatsorted = flat.slice().sort();
return flat.toString() === flatsorted.toString();
}
var grill = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log('grill sorted?', checkIfSorted(grill))
var grill2 = [
[1, 2, 4],
[3, 5, 6],
[7, 8, 9]
];
console.log('grill2 sorted?', checkIfSorted(grill2))
Upvotes: 1