Reputation: 21
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;
}
Upvotes: 0
Views: 131
Reputation: 3598
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));
Upvotes: 0
Reputation: 41893
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));
Upvotes: 4