Algorithm problem: Array Chunk

Faizah Ahsan
2 min readSep 27, 2020

--

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

  1. Create empty array to hold chunks called ‘chunked’
  2. For each element in ‘unchunked’ array
  3. Retrieve the last element in ‘chunked’
  4. If last element does not exist, or if it’s length is equal to chunk size
  5. Push a new chunk into ‘chunked with the current element
  6. Else add the current element into the chunk

Solution 2: Using .slice()

  1. Create empty ‘chunked’ array
  2. Create ‘index’ start at 0
  3. While index is less than array.length
  4. Push a slice of length ‘size’ from ‘array’ into ‘chunked’
  5. Add ‘size’ to ‘index’

--

--

Faizah Ahsan
Faizah Ahsan

Written by Faizah Ahsan

Junior Full-Stack Web Developer. Looking for opportunities!

No responses yet