split array into batches javascript code example

Example 1: array chunk javascript

let input = [1,2,3,4,5,6,7,8,9];
let chunked = []
let size = 2;

for (let i = 0;  i < input.length; i += size) {
  chunked.push(input.slice(i, i + size))
}
console.log(chunked)

Example 2: javascript how to split array into subarrays javascript

// Example array.
let randomArray = [3, 5, 1, 5, 7,];
// Create an empty array.
let arrayOfArrays = [];

function splitArray( array ) {
    while (array.length > 0) {
        let arrayElement = array.splice(0,1);
        arrayOfArrays.push(arrayElement);
    }
    return arrayOfArrays;
}

// Call the function while passing in an array of your choice.
splitArray(randomArray)
// => [ [ 3 ], [ 5 ], [ 1 ], [ 5 ], [ 7 ] ]