Algorithm problem: Array Chunk
This is another algorithm problem which might be asked at interviews often.
Before we start, let’s refresh our memory about arrays. What is an array?
An array is a special variable, which can hold more than one value at a time. An array can hold many values under a single name, and you can access the values by referring to an index number.
Ex: var fruits = [“Apple”, “Orange”, “Banana”]
What is array chunking?
Basically, you will have an array and a size, where will need to divide the array into many sub arrays where each sub array is of length size. In other words, Array chunking is a technique used to split very large arrays into smaller groups(sizes) usually for easier manipulation and presentation.
Example:
chunk([1,2,3,4], 2) → [[1,2], [3,4]]
chunk([1,2,3,4,5], 2) → [[1,2],[3,4],[5]]
chunk([1,2,3,4,5], 4) → [[1,2,3,4], [5]]
In the examples above you can they the array are divided into smaller chunks. Each subarray is a length 2, which we passed as size. So the two doesn’t mean we will need to have two different arrays, instead it means that each array will have 2 elements in each array. If you look at the third example you will have a better idea.
Solution 1: Looping
- Create empty array to hold chunks called ‘chunked’
- For each element in ‘unchunked’ array
- Retrieve the last element in ‘chunked’
- If last element does not exist, or if it’s length is equal to chunk size
- Push a new chunk into ‘chunked with the current element
- Else add the current element into the chunk
Solution 2: Using .slice()
- Create empty ‘chunked’ array
- Create ‘index’ start at 0
- While index is less than array.length
- Push a slice of length ‘size’ from ‘array’ into ‘chunked’
- Add ‘size’ to ‘index’