Tell us what’s happening:
Is there a way to combine the two for-loops?
I’ve gone about this problem in a very different (wrong?) way to what the hints page would have me do it, but hey. I hope this solution is at least interesting…
Your code so far
function chunkArrayInGroups(arr, size) {
//create an array for the result arrays
let resultArr = []
//go through elements of the array
for (let i = 0; i < arr.length; i += size){
//create sufficient sub-arrays
resultArr[i/size] = [];
}
for (let i = 0; i < arr.length; i++) {
//populate sub-arrays
resultArr[Math.floor(i/size)].push(arr[i])
}
return resultArr;
}
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
set a variable equal to an empty array, use a while() loop for that arrays length, then use the variable you set equal to an empty bracket to .push the array and size parameter back into that array, then return the variable set equal to the empty array
I’m not quite understanding – should the while() loop be within the for() loop? I’d like to combine the for( let i = 0; i < arr.length; i += size) and the for( let i = 0; i < arr.length; i ++) loops so that I only have to iterate over the array once.
No you should only declare a variable using the var keyword then set it equal to an empty array, then do a while loop with the array’s length in the parenthesis, then use the var name of the empty array to push the new array. like this : (variablename).push(define the method used to split arrays(with its index and size parameter ) {
finally return that initialised variable
}
Thanks Jeremy, In what instances should you use the var keyword? I understand that const can be used because an empty array will remain that way lest you insert content.
You should not use var. It is an outdated legacy feature.
Using const doesn’t really have anything to do with the array being empty. You should use const when you a) have a primative value you won’t change or b) have an array or object what you may updant but won’t fully replace. You use let if you can’t use const.