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;
}
You don't need to sort your array to check if it's sorted. Loop over each consecutive pair of elements and check if the first is less than the second; if you find a pair for which this isn't true, the array is not sorted.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
The average and worst-case complexity for your algorithm to check if an array is unsorted is O(N) . But the best-case complexity is O(1) .
To sort an array of arrays in JavaScript, we can use the array sort method. We call array. sort with a callback that destructures the first entry from each nested array. Then we return the value to determine how it's sorted.
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))
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With