Challenge this time is to 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.The clues are as given below:
The
push()
method adds one or more elements to the end of an array and returns the new length of the array.The syntax is as follows:
arr.push(element1, ..., elementN)
elementN
- The elements to add to the end of the array.
The
slice()
method extracts a section of a string and returns a new string.
The syntax is as follows;
str.slice(beginSlice[, endSlice])
beginSlice
- The zero-based index at which to begin extraction.
endSlice
- Optional. The zero-based index at which to end extraction.
- So below is my solution of the challenge:
function chunk(arr, size) {
newArray = [];
for (var i = 0; i < arr.length; i+=size){
var x = arr.slice(i, i+size);
newArray.push(x);
}
return newArray;
}
No comments:
Post a Comment