在 JavaScript 中对数组进行分块


我们需要编写一个 chunk() 函数,它将数组 arr 作为第一个参数,字符串/数字文字 arr 作为第二个参数。

我们需要返回一个由 n 个子数组组成的数组,每个子数组最多包含 arr.length / n 个元素。元素分布应如下 -

第一个元素在第一个子数组中,第二个在第二个子数组中,第三个在第三个子数组中,依此类推。当每个子数组中只有一个元素,我们再次开始填充第一个子数组的第二个元素。同样,当所有子数组只有两个元素时,我们在第一个数组中填充第三个元素,依此类推。

例如 −

// if the input array is:
const input = [1, 2, 3, 4, 5, 6];
//then the output should be:
const output = [
   [1, 4],
   [2, 5],
   [3, 6]
];

让我们编写此函数的代码,我们将 Array.prototype.reduce() 方法应用于原始数组以构造所需的数组。代码如下 -

示例

const input = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const chunk = (arr, size) => {
   return arr.reduce((acc, val, ind) => {
      const subIndex = ind % size;
      if(!Array.isArray(acc[subIndex])){
         acc[subIndex] = [val];
      } else {
         acc[subIndex].push(val);
      };
      return acc;
   }, []);
};
console.log(chunk(input, 4));

输出

控制台中的输出将是 −

[ [ 1, 5, 9 ], [ 2, 6 ], [ 3, 7 ], [ 4, 8 ] ]

更新时间:2020 年 8 月 25 日

697 次浏览

开始你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.