I have seen the solutions using push and slice but I wanted to achieve this using nested loops. When the number of elements in array are divisible by size, this code works but it doesn't work for other cases.
let arr2d = [];
function breakIt(arr, size){
if(arr.length % size === 0){
for (var i = 0; i < size; i++) {
arr2d[i] = new Array(size);
}
console.log(arr2d);
let increm = 0;
for(let i = 0; i < (arr.length/size); i++){
for(let j = 0; j < size; j++){
arr2d[i][j] = arr[increm];
increm++;
//console.log(arr2d[i][j]);
}
}
} else {
console.log('Odd number of elements in arr');
}
console.log(arr2d);
}
breakIt(["a", "b", "c", "d"], 2);
breakIt(["a", "b", "c", "d", "e", "f"], 3);
breakIt([1, 2, 3, 4, 5, 6], 2);
//breakIt([0, 1, 2, 3, 4, 5], 4)should return [[0, 1, 2, 3], [4, 5]]