Rose Rose - 5 months ago 54
Javascript Question

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 am working through a javascript problem that asks me to:

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

For example, the input

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


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

I can get it to work for most examples but when there are more than 2 chunks it switches the order and I am not sure why. Here is the code that I have written:

function chunk(arr, size) {
var newArray = [],
i, temp = arr;
for (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);

Answer

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