Skip to content
the poor coder

chunk an array

Poor Man
Published
Reading time
2 min read
On this page

Chunk an Array#

Chunking an array means splitting it into smaller arrays with a specific size. For example, if we have an array of 10 elements and we want to chunk it into arrays of 3 elements each, we would end up with 4 smaller arrays: [0, 1, 2], [3, 4, 5], [6, 7, 8], and [9].

Method 1: Using a for loop#

We can use a for loop and the slice method to create chunks of the array:

JavaScript

function chunkArray(arr, size) {
  const chunks = [];

  for (let i = 0; i < arr.length; i += size) {
    chunks.push(arr.slice(i, i + size));
  }

  return chunks;
}

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArray = chunkArray(myArray, 3);

console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this example, we start by creating an empty array called chunks that we will eventually fill with the smaller arrays. We then loop through the original array and increment the loop counter by the chunk size. For each iteration of the loop, we use the slice method to extract a portion of the original array and add it to the chunks array with the push method.

Method 2: Using the splice method#

Another way to chunk an array is to use the splice method:

JavaScript

function chunkArray(arr, size) {
  const chunks = [];

  while (arr.length > 0) {
    chunks.push(arr.splice(0, size));
  }

  return chunks;
}

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunkedArray = chunkArray(myArray, 3);

console.log(chunkedArray); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this example, we again start by creating an empty array called chunks. We then use a while loop to repeatedly extract portions of the original array using the splice method until the original array has been fully emptied. For each iteration of the loop, we add the extracted portion to the chunks array with the push method.

Both of these methods are effective for chunking an array, but you may want to choose one over the other depending on the specific use case and performance requirements.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC