Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice Array into an array of arrays

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.

like image 583
Grizzly Avatar asked Dec 15 '22 00:12

Grizzly


1 Answers

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)

like image 71
RomanPerekhrest Avatar answered Jan 02 '23 20:01

RomanPerekhrest