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


i working through javascript problem asks me to:

write function splits array (first argument) groups length of size (second argument) , returns them multidimensional array.

for example, input

chunk([0, 1, 2, 3, 4, 5], 2) 

should return 'chunked arrays': [[0, 1], [2, 3], [4, 5]]

i can work examples when there more 2 chunks switches order , not sure why. here code have written:

function chunk(arr, size) {   var newarray = [],       i, temp = arr;   (i = 0;i<= arr.length-size;i+=size){     newarray.push(arr.slice(i,i+size));     temp.splice(i,size);   }   newarray.push(temp);   return newarray; } chunk(['a', 'b', 'c', 'd'], 2); 

another version:

function chunk(arr, size) {     var result = [];     while (arr.length > size) {         result.push(arr.splice(0, size))     }     if (arr.length)         result.push(arr);      return result; } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -