Split Array Into N Chunks

JavaScriptJavaScriptBeginner
Practice Now

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28620{{"`Split Array Into N Chunks`"}} javascript/data_types -.-> lab-28620{{"`Split Array Into N Chunks`"}} javascript/arith_ops -.-> lab-28620{{"`Split Array Into N Chunks`"}} javascript/comp_ops -.-> lab-28620{{"`Split Array Into N Chunks`"}} javascript/destr_assign -.-> lab-28620{{"`Split Array Into N Chunks`"}} end

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.

Other JavaScript Tutorials you may like