Learning to chunk an array with JavaScript

ยท

2 min read

Learning to chunk an array with JavaScript

Instructions

Given the array and chunk size, divide the array into multiple subarrays where each is of similar length

//EXAMPLES
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, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]

Solution - Checking the last element

To start with create an empty array called "chunked". Then loop through each element of the given array. Inside the for loop get the last element of the chunked array. If the last element does not exist , or if its length is equal to the chunk size. Push new chunk with the current element to the chunked array. Else push the current element into the last chunk. Finally returning the chunked array

function chunk(array, size) {
  const chunked = []

  // loop through given array
  for (let element of array) {
    //get the last element chunked
    const last = chunked[chunked.length - 1]
    // if the last element does not exist, or if its length is equal to chunk size
    if (!last || last.length === size) {
      // push new chunk with current element
      chunked.push([element])
    } else {
      // push current element into chunk
      last.push(element)
    }
  }

  return chunked
}

chunked-repeat-24.gif

Solution - Slice

The same outcome can be achieved by using the slice array method. Keep in mind the second parameter in slice is not the length. Its the element in the array to slice up to not including it

const nums= [1,2,3,4,5]

nums.slice(0,3) // [1,2,3]

To start, create a empty chunked array and index integer starting at 0. Then loop through the array using a while loop. Slice the array at the current index to the index + chunk size. Push the sliced array to the chunked array. Finally return the chunked array

const chunk= (array, size) => {
    //create emtpy arry
  const chunked = []
    //current index
  let index = 0

  while (index < array.length) {
    //push chunked array to chunked
    chunked.push(array.slice(index, index + size))
    //increase index by size
    index += size
  }
  return chunked
}
ย