切片数组并制作多维数组

时间:2018-01-27 17:51:07

标签: javascript arrays for-loop

我需要使用for loop以及slice()push()方法切片和数组。

我尝试了一切可能的方法(显然除了正确的方法),但无法找出解决方案。

请解释一下,因为在递归和循环方面,我总是遇到麻烦。

 function chunkArrayInGroups(arr, size) {
  // Break it up.
  var finalArray = [];

  // var firsPart = arr.slice(0, 2);
  // var secondPart = arr.slice(2, 4);
  // console.log(firsPart);
  // console.log(secondPart);

  // finalArray.push(firsPart, secondPart);

  for (var i = 0; i < arr.length; i++) {
    var slicingIndex = 0;
    var sliced = arr.slice(size);

    finalArray.push(sliced);
    }

  return finalArray;
}

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

你可以使用带有索引的while循环和切片以及带有所需长度的更新索引。

function chunkArrayInGroups(arr, size) {
    var finalArray = [],
        i = 0;

    while (i < arr.length) {
        finalArray.push(arr.slice(i, i += size));
    }
    return finalArray;
}

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

绝不是专家,但我认为这可能有所帮助。

function chunkArrayInGroups(arr, size) {
  var finalArray = [];

  for (var i = 0; i < size; i++) {
    if (finalArray.length !== size) {
      var sliced = arr.slice(i);
      finalArray.push(sliced);
    }
  }

  return finalArray;
}

console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 3));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 2));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6], 3));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 4));
console.log(chunkArrayInGroups([0, 1, 2, 3, 4, 5, 6, 7, 8], 2));