0

everyone, I'm stuck. The function isGrid returns true if twoD is an array of arrays in that each row has the same number of columns, it returns false otherwise. I'm think I'm supposed to compare the length of two of the functions but I'm stuck

    function isGrid(twoD) {
        var isMatrix = true;
        while(twoD.length!==isGrid)
             isMatrix= false; 
    }  
        return isMatrix;
    }
1
  • 3
    This is has no sense twoD.length!==isGrid! Commented Apr 3, 2017 at 20:26

2 Answers 2

4

You could use Array#every to determine if every nested array of given array has the same length by comparing it to e.g. the first nested array.

var arr1 = [[1,2,3], [1,2,3]],
    arr2 = [[1,2], [1,2,3]];
    
    function check(arr){
      return arr.every(v => v.length == arr[0].length);
    }
    
    console.log(check(arr1));
    console.log(check(arr2));

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

1 Comment

Array.isArray(arr) && arr.every(v => Array.isArray(v) && v.length == arr[0].length) Checking that the objects are arrays may be worthwhile as well.
0

Here is working example. I refactored your code a little bit. Pure javascript, no ES6 helpers.

var example1 = [[1,2], [1,2], [1,2], [1,2], [1,2]],
		example2 = [[2,2], [1,1]],
    example3 = [[1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4], [1,2,3,4]];
		
function isGrid(twoD) {
  var isMatrix = true;
  var arrayToCompare = twoD[0];

  // We start from second element in Array
  for (i = 1; i < twoD.length; i++) {
    var compareWith = twoD[i];

    for (j = 0; j < arrayToCompare.length; j++) {
      var arrayToCompareElements = arrayToCompare[j];

      //console.log(arrayToCompareElements, compareWith[j]);

      if (arrayToCompareElements !== compareWith[j]) {
        isMatrix = false;
        break;
      }
    }


    arrayToCompare = compareWith;
  }

  return isMatrix;
}

console.log(isGrid(example1));
console.log(isGrid(example2));
console.log(isGrid(example3));

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.