Javascript Array chunkArrayInGroups(arr, size)

Description

Javascript Array chunkArrayInGroups(arr, size)


/*/*from  w  ww.  j a v a  2 s  .c o m*/

Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.

Remember to use Read-Search-Ask if you get stuck. Write your own code.

Here are some helpful links:

Array.prototype.push()
Array.prototype.slice()

*/

function chunkArrayInGroups(arr, size) {
  var newArray = [];
  
  for (var i = 0; i < arr.length; i += size) {
    newArray.push(arr.slice(i, size + i));
  }  
  
  return newArray;        
}

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));

Javascript Array chunkArrayInGroups(arr, size)



function chunkArrayInGroups(arr, size) {
  // Break it up.
  var newArr = [];
  i = 0;/*from  www .j  a  va2s  .c om*/
  while (arr.length > size) {
    // grab first "size" elements from array
    newArr[i] = arr.slice(0,size);
    // remove first "size" elements from array
    for (j = 0; j < size; j++) {
      arr.shift();
    }
    i += 1;
  }
  newArr[i] = arr;
  return newArr;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);



PreviousNext

Related