Split Into Chunks

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to split an array into smaller arrays of a specified size using JavaScript. We will use the Array.from() and Array.prototype.slice() methods to create a new array that contains the specified number of chunks. We will also learn how to handle cases where the original array cannot be split evenly.

How to Split an Array into Chunks of a Specific Size

To practice coding, open the Terminal/SSH and type node.

To split an array into smaller arrays of a specified size, follow these steps:

  1. Use Array.from() to create a new array that fits the number of chunks that will be produced.
  2. Use Array.prototype.slice() to map each element of the new array to a chunk the length of size.
  3. If the original array cannot be split evenly, the final chunk will contain the remaining elements.

Here's an example code snippet:

const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );

You can use this function by passing in the array you want to split and the desired size of the chunks. For example:

chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]

Summary

Congratulations! You have completed the Split Into Chunks lab. You can practice more labs in LabEx to improve your skills.