Split Array Into N Chunks

Beginner

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

Introduction

In this lab, we will explore the topic of array manipulation in JavaScript. Specifically, we will focus on the task of splitting an array into smaller chunks of a specified size. Through this lab, you will learn how to use built-in JavaScript methods to efficiently and effectively manipulate arrays. By the end of this lab, you will have gained a deeper understanding of array manipulation in JavaScript and be able to apply these skills to solve real-world problems.

How to Split an Array into N Chunks

To split an array into n smaller arrays, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use Math.ceil() and Array.prototype.length to calculate the size of each chunk.
  3. Use Array.from() to create a new array of size n.
  4. Use Array.prototype.slice() to map each element of the new array to a chunk the length of size.
  5. If the original array cannot be split evenly, the final chunk will contain the remaining elements.

Here is an example implementation of the chunkIntoN function in JavaScript:

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

You can use this function to split an array into n chunks by passing the array and the desired number of chunks as arguments. For example:

chunkIntoN([1, 2, 3, 4, 5, 6, 7], 4); // [[1, 2], [3, 4], [5, 6], [7]]

Summary

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