如何在JavaScript中把一个数组分割成一个数组

151 阅读1分钟

有时我们有一个数组,我们可能想把它分成多个数组。这里有一个快速而简单的方法来做到这一点。

问题所在

假设我们有下面这个数组。

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

不管出于什么原因,我们需要把它分成三个子数组,像这样。

const result = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
];

我们怎样才能做到这一点呢?

一个快速的解决方案

一个快速的解决方案是如下。重要的是,这将创建一个新的results 数组,而不会改变 nums 数组。

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9];

// Get number of elements per subarray
const numsPerGroup = Math.ceil(nums.length / 3);
// Create array based on number of groups
const result = new Array(3)
  // Make sure each element isn't empty
  .fill('')
  // For each group, grab the right `slice` of the input array
  .map((_, i) => nums.slice(i * numsPerGroup, (i + 1) * numsPerGroup));

这样做很有效!然而,每当我想出这样一个整洁的解决方案时,我都想看看是否能将其抽象成一个可重用的函数。

一个可重用的createGroups函数

为了使这个函数可以重复使用,我们只需要把代码放在一个函数中,用用户提供的参数替换数字3nums 数组。

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]]

它的效果很好!