Hey guys! Having some trouble trying to make the rest of the arrays split into the size of “size”. I have got the first array to be the size of “size”, but the rest of the characters are all put into one array. I also don’t know where to implement the loop. Thanks!
function chunkArrayInGroups(arr, size) {
let newArr=[]
let result=0;
for (let i=0;i<arr.length;i++) {
result=arr.splice(0,size)
newArr.push(result)
}
return newArr
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36.
Am I using the loop correctly? I have tried using slice but it keeps giving me the first array 4 times over. Do I need to use [i] anywhere for this implementation? Thanks!
I tried using i++ and if I use [i], it has to be on arr right? I tried size[i] and got some weird results. Here is what I have so far but it’s just returning the original array. It’s a bit hard grasping the application of [i] and how it will all come together.
function chunkArrayInGroups(arr, size) {
let newArr=[]
let result=0;
for (let i=0;i<arr.length;i++) {
result=arr[i].slice(0,size)
i++
newArr.push(result)
}
return newArr
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
I have to figure out the adjustment I have to make to i after each iteration. And I don’t increment by one (i++), I have tried i+size, or size++. Both yield wrong results. Will try a little longer on this one
for (let i=0;i<arr.length;i++) {
result=arr.slice(i,size)
newArr.push(result)
I appreciate you walking me through it. I had forgotten that you can use more than just the i++ or i-- operators in the loop. I googled different operators you can use to increment with (stackoverflow) and discovered the += operator. I used that in conjunction with size which allowed me to use size in the declaration (which I previously though was impossible). Then I fiddled with the second argument until I got to size+i. Which is still foggy to me, it was the console that helped me on that one. I really need to review some stuff…
Here is the passing code:
function chunkArrayInGroups(arr, size) {
let newArr=[]
let result=0;
for (let i=0;i<arr.length;i+=size) {
result=arr.slice(i,size+i)
newArr.push(result)
}
return newArr
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));