I am sorry but I still couldn’t figure it out even after adding the console.logs. The undefined warning makes me think that I am trying to manipulate an element of an array that’s not defined but am I not supposed to declare an empty array? Why would it be defined anyways?
function chunkArrayInGroups(arr, size) {
let myArr = [];
let counter = arr.length / size;
let base = 0;
for(let i = 0; i < counter; ++i){
let subArray = 0;
for(let a = 0; a < size; ++a) {
myArr[i][subArray] = arr[base];
++subArray;
++base;
}
}
console.log(myArr);
return myArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3);
So, myArr[i] is not defined. But, if myArr[i] is not defined, then it is impossible for myArr[i][anything] to exist. You can’t assign something to a property/index of a thing that doesn’t exist.
You can add values to an empty array. But that’s not what you are doing. You are trying to add values to a subarray of an empty array.
// This is ok
const myArray = [];
myArray[2] = 5;
console.log(myArray);
// This is bad
const mySecondArray = [];
mySecondArray[0][2] = 5;
console.log(mySecondArray);
Okay, I see what I was doing wrong and I was able to pass the challenge using .push(), but I am curious if there is a way to create subarrays of an empty array without using .push function.
Sure, you just need to define mySecondArray[0] before trying to use it:
// This is ok
const myArray = [];
myArray[2] = 5;
console.log(myArray);
// This is ok but wierd
const mySecondArray = [];
mySecondArray[0] = [];
mySecondArray[0][2] = 5;
console.log(mySecondArray);
// This is bad
const myThirdArray = [];
myThirdArray[0][2] = 5;
console.log(myThirdArray);