将数组切成数组

Gri*_*zly 3 javascript arrays

如果我有一个功能:

function sliceArrayIntoGroups(arr, size) {
  var slicedArray = arr.slice(0, size);

  return slicedArray;
}
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个数组并将其切成数组的数组..我该怎么做呢?

所以,如果我有这个:

sliceArrayIntoGroups(["a", "b", "c", "d"], 2);
Run Code Online (Sandbox Code Playgroud)

结果应为:

[["a","b"],["c","d"]]
Run Code Online (Sandbox Code Playgroud)

但是我不知道在切片后如何保存原始数组的第二部分。

任何帮助表示赞赏。

Rom*_*est 5

使用常规while循环和自定义step参数的解决方案:

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));
Run Code Online (Sandbox Code Playgroud)

step 选项指向每个提取的偏移量(切片)