If I have a function:
function sliceArrayIntoGroups(arr, size) {
var slicedArray = arr.slice(0, size);
return slicedArray;
}
I am looking to take an array and slice it into an array of arrays.. how would I go about doing so?
So if I had this:
sliceArrayIntoGroups(["a", "b", "c", "d"], 2);
The result should be:
[["a","b"],["c","d"]]
But I don't know how to save the second part of the original array after slicing it.
Any help is appreciated.
The solution using regular while
loop and custom step
parameter:
function sliceArrayIntoGroups(arr, size) {
var step = 0, sliceArr = [], len = arr.length;
while (step < len) {
sliceArr.push(arr.slice(step, step += size));
}
return sliceArr;
}
console.log(sliceArrayIntoGroups(["a", "b", "c", "d"], 2));
console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 2));
console.log(sliceArrayIntoGroups(["a", "b", "c", "d", "e", "f"], 3));
step
option points to an offset of each extraction(slicing)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With