cft

Learning to chunk and array in JavaScript

My notes from learning how to chunk and array in JavaScript


user

Delvoid

2 years ago | 2 min read

What is a chunked array?

An array chunked into smaller arrays of a specifed size. The last chunk may contain less elements than the specifed size but not more.

Instructions

Given an array and chunk size, divide the array into many subarrays where each subarray is of length size.

//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 we need to create a empty array called "chunked". Then loop through each element of the given array. Inside the for loop we need to get the last element of the chunked array we created. 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
}

Animated process of chunking the array

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
}

Upvote


user
Created by

Delvoid

šŸ‘‹ Hi, I’m Delvoid. I am currently focusing on learning Javascript, NodeJs with express for backend and react for frontend development. With the goal of finding a developer position.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles