分割数组–

2023年11月27日08:59:33

假设,我们需要编写一个函数,该函数将字符串/数字文字的数组arr作为第一个参数,将数字n作为第二个参数。

我们需要返回一个n个子数组的数组,每个子数组最多包含arr.length / n个元素。而且元素的分布应该像这样-

  • 第一个元素进入第一个子数组,第二个进入第二个子数组,第三个进入第三个子数组,依此类推。

  • 在每个子数组中都有一个元素后,我们再次从第一个子数组中填充第二个元素开始。

  • 同样,当所有子数组只有两个元素之后,我们才将第一个元素填充到第三个数组中,依此类推。

例如-

如果输入数组是-

 
const input = [656, 756, 5345, 67, 43, 76, 54, 768, 34];

并且数字n为3,则输出应为-

const output = [
   [ 656, 67, 54 ],
   [ 756, 43, 768 ],
   [ 5345, 76, 34 ]
];

我们将在原始数组上使用Array.prototype.reduce()方法来构造所需的数组。

示例

以下是代码-

const input = [656, 756, 5345, 67, 43, 76, 54, 768, 34];
const divideArray = (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(divideArray(input, 3));

输出结果

这将在控制台中产生以下输出-

[ [ 656, 67, 54 ], [ 756, 43, 768 ], [ 5345, 76, 34 ] ]

  • 更新时间:2023年11月27日08:59:33 ,共 869 字。