divide array into equal parts javascript code example

Example 1: how to divide array in two parts in js

function chunkArray(arr,n){
     var chunkLength = Math.max(arr.length/n ,1);
     var chunks = [];
     for (var i = 0; i < n; i++) {
         if(chunkLength*(i+1)<=arr.length)chunks.push(arr.slice(chunkLength*i, chunkLength*(i+1)));
     }
     return chunks; 
 }

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 ] ]