Chunky Monkey (why I can't do math on the second argument of For)

Chunky Monkey (why I can't do math on the second argument of For)
0.0 0

#1

Hi,

I have found the solution to the Chunky Monkey challenges, however, I don’t know why I had to create a variable for the math that I was trying to add to the second argument of for.

I mean It works …

let division = Math.ceil(arr.length/size)
for (let x=1; x<=division;x++){

but it didn’t work

for (let x=1; x<=Math.ceil(arr.length/size);x++){

It is possible to declare math on it?


function chunkArrayInGroups(arr, size) {

let newArr = [];
let division = Math.ceil(arr.length/size)
for (let x=1; x<=division;x++){
  newArr.push(arr.splice(0,size));
}
return newArr;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);



#2

Since splice changes arr’s length, your calculation of arr.length/size would be different each time. You want it to be the same, which is why you had to create a variable to hold the number splices that will take place (your variable named division).


#3

This way, calculate the division, and keep it in a variable.

but:

for each iteration(loop) this Math.ceil(arr.length/size) is called, while first approach uses the cached(only once) value.

Now in your code, you push new element on array, so for next iteration(if second form) the Math.ceil() result different value, while the var(first approach) doesn’t(unless you make the var as a function call to do that Math again)

Depends on case-study, you may better go for first way, or second way. There is no rule.