how to divide an array in javascript code example

Example 1: javascript split array into chuncks of

function splitArrayIntoChunksOfLen(arr, len) {
  var chunks = [], i = 0, n = arr.length;
  while (i < n) {
    chunks.push(arr.slice(i, i += len));
  }
  return chunks;
}
var alphabet=['a','b','c','d','e','f'];
var alphabetPairs=splitArrayIntoChunksOfLen(alphabet,2); //split into chunks of two

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

Example 3: split array into chunks javascript

Array.prototype.chunk = function(size) {
    let result = [];
    
    while(this.length) {
        result.push(this.splice(0, size));
    }
        
    return result;
}

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(arr.chunk(2));