Hi,
I just solved the Chunkey Monkey Challenge and I’d like some feedback. Something tells me I could have solved this more efficiently. I feel like there was probably a way I could have modified the array in place.
My Solution
function chunkArrayInGroups(arr, size) {
var newArr = [];
var count = 0;
while (count < arr.length){
newArr.push(arr.slice(count,(size + count)));
count += size;
}
return newArr;
}
What I wanted to do, in English, was “Take the given array, remove x number of items from the array and place them in a new array”. Instead of removing them, my code is copying them then starting the slice after the given count for them.
Is there a way to move items from one array to another rather than to copy?
Another, less elegant solution I thought of would to have a for loop that ran the shift()
method the number of times given. Unfortunately, shift()
doesn’t take any params.
Our solutions are the same, except that I used a for-loop.
Even the solutions in the wiki look like that.
1 Like
Thanks. As for the wiki you’re referring to, is there a FCC specific wiki, or something else?
this is my solution, quite simple really
function chunkArrayInGroups(arr, size) {
var original = arr;
var collector = [];
var starter = 0;
counter = 0;
while (counter < arr.length/size) {
var adder = arr.slice(starter,starter+size);
Array.prototype.push.apply(collector, [adder]);
counter++;
starter = starter + size;
}
return collector;
}
There’s a #wiki in the forum, and #wiki:fcc-algorithms list solutions for the algo challenges… This is the post for chunky monkey.
Thanks again. It looks like the intermediate solution is what I was looking for. Good to know that that page exists. I’m sure that was explained somewhere along my on/off use of FCC.
And I agree with some of the posters. Apparently, my first solution is considered the “Advanced” solution. I think the “Intermediate” solution is cleaner, especially considering that the for loop runs operations faster than the while loop if I remember correctly.