让我们说我有一个Javascript数组看起来如下:

["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.

什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?


当前回答

我更喜欢使用拼接法而不是切片法。 这个解决方案使用数组长度和块大小来创建循环计数,然后循环遍历数组,在每个步骤中由于拼接而在每个操作后变得更小。

    function chunk(array, size) {
      let resultArray = [];
      let chunkSize = array.length/size;
      for(i=0; i<chunkSize; i++) {
        resultArray.push(array.splice(0, size));
      }
    return console.log(resultArray);
    }
    chunk([1,2,3,4,5,6,7,8], 2);

如果不想改变原始数组,可以使用展开操作符克隆原始数组,然后使用该数组来解决问题。

    let clonedArray = [...OriginalArray]

其他回答

一行程序

const chunk = (a,n)=>[...Array(Math.ceil(a.length/n))].map((_,i)=>a.slice(n*i,n+n*i));

为打印稿

const chunk = <T>(arr: T[], size: number): T[][] =>
  [...Array(Math.ceil(arr.length / size))].map((_, i) =>
    arr.slice(size * i, size + size * i)
  );

DEMO

const块= (n) = >[…]数组(Math.ceil (a.length / n))) . map ((_, i) = > a.slice (n * n + n * i)); document . write (JSON。Stringify (chunk([1,2,3,4], 2)));

按组数分组

const part=(a,n)=>[...Array(n)].map((_,i)=>a.slice(i*Math.ceil(a.length/n),(i+1)*Math.ceil(a.length/n)));

为打印稿

const part = <T>(a: T[], n: number): T[][] => {
  const b = Math.ceil(a.length / n);
  return [...Array(n)].map((_, i) => a.slice(i * b, (i + 1) * b));
};

DEMO

Const部分= (a, n) => { const b = Math.ceil(a。长度/ n); 返回数组(n)[…]。Map ((_, i) => .slice(i * b, (i + 1) * b)); }; document . write (JSON。Stringify (part([1,2,3,4,5,6], 2))+'<br/>'); document . write (JSON。Stringify (part([1,2,3,4,5,6,7], 2)));

这里有一个更具体的案例,有人可能会觉得有价值。我还没看到这里提到过。

如果你不想要固定/均匀的数据块大小,而是想要指定拆分数组的下标怎么办?在这种情况下,你可以使用这个:

const splitArray = (array = [], splits = []) => {
  array = [...array]; // make shallow copy to avoid mutating original
  const chunks = []; // collect chunks
  for (const split of splits.reverse()) chunks.push(array.splice(split)); // go backwards through split indices and lop off end of array
  chunks.push(array); // add last remaining chunk (at beginning of array)
  return chunks.reverse(); // restore chunk order
};

然后:

splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6]) 
// [ [1, 2, 3, 4] , [5, 6] , [7, 8, 9] ]

请注意,如果你给它非升序/重复/负/非整数/等分割索引,这将会发生有趣的事情。您可以为这些边缘情况添加检查(例如array .from(new Set(array))来消除重复。

我试过递归函数…

const chunk = (arr, n) =>
    arr.length ? [arr.slice(0, n), ...chunk(arr.slice(n), n)] : [];

……这很好,很短,但似乎是@AymKdn回答1000个元素用时的256倍,10000个元素用时的1058倍!

当前排名靠前的答案存在的问题是,它们产生了不平衡的数据块。例如,当前接受的答案将把一个101个元素的数组分布为10个大小为10的块,后面是一个大小为1的块。

使用一些模块化算法可以创建统一的块大小,差异永远不会超过1:

函数split_array(a, nparts) { const quot = Math.floor;长度/ nparts) Const rem = a.length % nparts Var部件= [] For (var I = 0;I < nparts;+ + i) { const begin = i * quot +数学。分钟(rem,我) Const end = begin + quot + (i < rem) parts.push (a。片(开始、结束) } 返回部分 } Var chunk = split_array([1,2,3,4,5,6,7,8,9,10], 3) console.log (JSON.stringify(块)

输出:

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

(摘自相关答案)

你可以使用这个ES6块函数,它很容易使用:

Const chunk = (array, size) => Array.from({长度:Math.ceil(数组。Length / size)}, (value, index) =>数组。切片(索引*大小,索引*大小+大小)); const itemsPerChunk = 3; const inputArray = [a, b, c, d, e, f, g的); const newArray = chunk(inputArray, itemsPerChunk); console.log (newArray.length);/ / 3, document . write (JSON.stringify (newArray));/ / [[' a ', ' b ', ' c '], [' d ', ' e ', ' f '], [g]]