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

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

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


当前回答

这是我使用的,它可能不是超级快,但它是紧凑和简单:

让chunksplit = (stream, size) => stream。Reduce ((chunk, item, idx, arr) => (idx % size == 0) ?[…块,加勒比海盗。Slice (idx, idx + size)]: chunk, []); //如果索引是chunksize的倍数,则添加新数组 让testArray =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12日,13日,14日,15日,16日,17日,18日,19日,20日,21日,22日); document . write (JSON。stringify(chunksplit(testArray, 5)); / /使用JSON。要显示的嵌套数组的Stringify

其他回答

如果你正在使用下划线JS,只需使用:

var result = _.chunk(arr,elements_per_chunk)

无论如何,大多数项目已经使用下划线作为依赖项。

使用发电机

函数*块(arr, n) { 对于(设I = 0;I < arrr .length;I += n) { 加勒比海盗。Slice (i, i + n); } } let someArray = [0,1,2,3,4,5,6,7,8,9] console.log([…块(someArray, 2)]) / /[[0, 1],[2、3],[4,5],[6、7],[8 9]]

可以像这样用Typescript输入:

function* chunks<T>(arr: T[], n: number): Generator<T[], void> {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n);
  }
}

一行程序

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)));

下面是一个例子,我将一个数组分割成2个元素的块,只需从数组中拼接块,直到原始数组为空。 Const数组= [86,133,87,133,88,133,89,133,90,133]; Const new_array = []; Const chunksize = 2; While (array.length) { Const chunk = array.splice(0,chunksize); new_array.push(块); } console.log (new_array)

下面的ES2015方法不需要定义函数,直接在匿名数组上工作(例如块大小为2):

[11,22,33,44,55].map((_, i, all) => all.slice(2*i, 2*i+2)).filter(x=>x.length)

如果你想为此定义一个函数,你可以这样做(改进K._对Blazemonger的回答的评论):

const array_chunks = (array, chunk_size) => array
    .map((_, i, all) => all.slice(i*chunk_size, (i+1)*chunk_size))
    .filter(x => x.length)