HLJ 发布于
2021-07-30 16:08:54

在 JavaScript 中将数组拆分为n个数组

function createGroups(arr, numGroups) {
  const perGroup = Math.ceil(arr.length / numGroups);
  return new Array(numGroups)
  .fill('')
  .map((_, i) => arr.slice(i * perGroup, (i + 1) * perGroup));
}
console.log(createGroups(['cat', 'dog', 'pig', 'frog'], 2));
// 输出结果 [["cat", "dog"], ["pig", "frog"]]

console.log(createGroups([1, 2, 3, 4, 5], 3));
// 输出结果 [[1, 2], [3, 4], [5]]
当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2021-07-30/555.html
最后生成于 2022-10-07 22:27:45