Javascript Chunking Problem

I worked this problem a couple of ways from both Stephen Grider’s Udemy Course and Traversy Media’s YouTube course.

Below is solution 1.  I use a for…of loop.  First I determine what position the last element of the array would be (const last = chunked[chunked.length-1]).  I have to use chunked.length-1, because length counts the number of elements starting at 1, while the array index starts at 0.

The next line determines if there is no array (!last) or if the array size is at the current chunking size (last.length === size), then create a new chunked array and pass the current element into it.  Otherwise, push the current element into the array.

I also did the problem using another method.  Here I use the array.prototype.slice() method.  I was stuck for quite a while on this solution with it not working correctly.  I finally realized I had typed “splice” instead of “slice”.

I set i=0, to represent index 0 in the original array.  I create a new array – chunked – to hold the chunked numbers.  Then I use a while loop to go through the length of the original array.  Within the while loop,  I use array.slice to retrieve the smaller chunks.  The first time around it uses array.slice(0,2).  This means it will take index items 0 and 1 (the 2 means it stops at 2, but is not inclusive).  It then pushes those two numbers as a chunk into the new chunked array.

I then set i = i + size (i.e. 0 + 2 = 2).  Meaning the program will start on index item 2 in the next look and so on.  It will continue looping until all numbers have been “chunked.”  Note that if we are doing chunks of 2, but there is only one number remaining in the original array, it will simply create an array for that one number and add it to “chunked.”

I’m review this in 2019 and I came up with a new method.  I was trying to use map or another array method.  I didn’t get that to work, but I did come up with the solution below.  I use two for loops.  The outer loop increments based on size, or the chunking unit.  The inner array loops on the size counter.  If size is 2, the first loop will be positions 0 and 1.  The inside loop adds i from the outer loop to j from the inner loop.  0 + 0 is position 0.  0 + 1 is position 1.  So it will return index 0 and 1 to the inner array, then push the inner array to the outer array.  The outer array will then increment to positions 2 and 3. When the outer loop has finished running, it will return the outerArray.


Leave a Reply

Your email address will not be published. Required fields are marked *