I previously wrote about some common coding algorithms that you’ll run into on your job search. The article was received fairly well so I thought I’d do a couple more to help in your journey to becoming more familiar with algorithms.

CHUNKS

With this problem, you’ll be given an array and a chunk size. You’ll need to divide the array into subarrays that are the length of the chunk size and returned as a new array. In this exercise, we’ll be using a while loop as well as the array methods push and splice. Since we’ll be placing the subarrays into a new array, let’s go ahead and create an empty array at the top of our function.

Image for post

Now, let’s think about what we’re looking for. We want to create new arrays that are the length of the ‘size’ argument. So let’s cut the array into the size we want using the ‘splice’ array method to see what’ll happen.

Image for post

Please be careful with the ‘splice’ method as it can also be used to replace items in an array. Click the linked article to read more about that process.

As you can see in the terminal, we now have an array that has a length of 2, starting at the zero(0) index of the ‘arr’ variable on line 16. This is great but we still need the rest of the array AND to have it returned within a new array.

One way we can get the rest of the original array is to the splice the array while counting the length of the array.

Image for post

Alllllmost there

Nice One! The final step to this problem is pushing the results of our while loop/splice into the ‘arr2’ variable that we created earlier. The push method pushes an item to the end of the array that it is called on.

Image for post

You’re a coding wizard, Harry

Take a quick break for some water and snacks, then we’ll jump into the next problem.

#javascript-tips #coding-interviews #coding #javascript #algorithms

Coding Interviews: Common Algorithms
1.40 GEEK