Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if array of arrays is sorted javascript

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;
}
like image 287
Guaro Avatar asked May 11 '20 23:05

Guaro


People also ask

How do you check if the array is already sorted or not?

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.

Does sort mutate array JavaScript?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

What is the time complexity to check if an array is sorted or not?

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

Can you sort an array of arrays?

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.


2 Answers

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))
like image 55
Jaromanda X Avatar answered Sep 30 '22 22:09

Jaromanda X


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;
}
like image 38
elvira.genkel Avatar answered Sep 30 '22 22:09

elvira.genkel