7

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;
}
3
  • So actually all the elements should be in ascending order if they are flatten? The following should yield false: [[4,5,6],[1,2,3],[7,8,9]]? Commented May 12, 2020 at 1:38
  • yes, only case true : [[1,2,3],[4,5,6],[7,8,9]] Commented May 12, 2020 at 3:48
  • then you already got your response :) Commented May 12, 2020 at 7:01

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.