Signup/Sign In
PUBLISHED ON: MARCH 2, 2023

JavaScript Program to Split Array into Smaller Chunks

This tutorial will teach how to make a JavaScript Program to Remove Duplicates From Array. To understand this article we need to have a decent knowledge of JavaScript Array slice(), Array splice(), and JavaScript Arrays. It's an easy job that can be done with a few lines of code. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.

Split Array Using slice()

In the code given below, the for loop is used with the slice() method to split an array into smaller chunks of array.

The for loop iterates through the elements of an array. During each iteration, the value of i increased to

The slice() method has the following parameters:

  • The first argument specifies the starting index.
  • The second argument specifies the ending index.
// JavaScript Program to split array into smaller chunks

function splitIntoChunk(arr, chunk) {

    for (let i=0; i < arr.length; i += chunk) {

        let tempArray;
        tempArray = arr.slice(i, i + chunk);
        console.log(tempArray);
    }

}

const array = [1, 9, 18, 45, 53, 64, 72, 81];
const chunk = 2;
splitIntoChunk(array, chunk);


[ 1, 9 ]
[ 18, 45 ]
[ 53, 64 ]
[ 72, 81 ]

Split Array Using splice()

In the code given below, the while loop is used with the splice() method to split an array into smaller chunks of an array.

In the splice() method:

  • The first argument specifies the index where you want to split an item.
  • The second argument specifies the number of items to split.

The while loop is basically used to iterate over the whole array until the array is empty.

// JavaScript Program to split array into smaller chunks

function splitIntoChunk(arr, chunk) {

    while(arr.length > 0) {

        let tempArray;
        tempArray = arr.splice(0, chunk);
        console.log(tempArray);
    }
}

const array = [1, 21, 30, 45, 53, 64, 72, 81, 99, 108 ];
const chunk = 2;
splitIntoChunk(array, chunk);


[ 1, 21 ]
[ 30, 45 ]
[ 53, 64 ]
[ 72, 81 ]
[ 99, 108 ]

Conclusion

In conclusion, breaking an array into smaller chunks is a handy strategy for working with huge data sets and arrays in JavaScript. Using the slice or splice methods, it is simple to pluck elements from an array and generate new arrays. Using a for loop or while loop, a modulus operator, and a library are recommended techniques for slicing arrays into smaller halves.



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.