Data structures : chunked Array Challenge method One

preview_player
Показать описание
Chunking an Array
Let’s say we have an array of items, of undefined length, and we want to break it up into equal-sized subarrays to make it easier to work with. Maybe we want to be able to render groups of three user profiles at a time, or limit the number of images to load in a container before the user performs some action. It would be a very useful skill to have (which is perhaps why it’s a common interview question)!

So, starting with the problem:

Write a function that, when given an array and chunk size, will return a new array divided into many subarrays where each subarray is the chunk length

We know that we’ll want to iterate through our array, making new subarrays along the way (keeping track of the number of steps each time). This seems like it should be fairly tricky, however if we make smart use of an iterator and a very handy array method, we can come up with a pretty simple straightforward solution!

The key here will be to use the slice() method, available on all arrays. It allows us to grab a portion of an array, and spit out a new array object — which sounds just like what we’re trying to do! When called on an array, slice() takes two arguments, the beginning and ending indices (the ending one not included). Like so:
Рекомендации по теме
visit shbcf.ru