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

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

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


当前回答

我的目标是在纯ES6中创建一个简单的非突变解决方案。javascript的特性使得在映射之前必须填充空数组:-(

function chunk(a, l) { 
    return new Array(Math.ceil(a.length / l)).fill(0)
        .map((_, n) => a.slice(n*l, n*l + l)); 
}

这个带有递归的版本似乎更简单,也更引人注目:

function chunk(a, l) { 
    if (a.length == 0) return []; 
    else return [a.slice(0, l)].concat(chunk(a.slice(l), l)); 
}

ES6中荒谬的弱数组函数可以制作出很好的谜题:-)

其他回答

array.slice()方法可以根据需要从数组的开头、中间或结尾提取切片,而不需要改变原始数组。

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    // do whatever
}

最后一个块可能小于chunkSize。例如,当给定一个包含12个元素的数组时,第一个块将有10个元素,第二个块只有2个。

注意,chunkSize为0将导致无限循环。

你可以使用这个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]]

我试过递归函数…

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

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

好吧,让我们从一个相当严格的开始:

function chunk(arr, n) {
    return arr.slice(0,(arr.length+n-1)/n|0).
           map(function(c,i) { return arr.slice(n*i,n*i+n); });
}

它是这样使用的:

chunk([1,2,3,4,5,6,7], 2);

然后我们就有了这个紧密的减速器函数:

function chunker(p, c, i) {
    (p[i/this|0] = p[i/this|0] || []).push(c);
    return p;
}

它是这样使用的:

[1,2,3,4,5,6,7].reduce(chunker.bind(3),[]);

因为当我们将它绑定到一个数字时,小猫就死了,我们可以像这样手动curry:

// Fluent alternative API without prototype hacks.
function chunker(n) {
   return function(p, c, i) {
       (p[i/n|0] = p[i/n|0] || []).push(c);
       return p;
   };
}

它是这样使用的:

[1,2,3,4,5,6,7].reduce(chunker(3),[]);

然后是仍然非常紧凑的函数,它可以一次性完成所有操作:

function chunk(arr, n) {
    return arr.reduce(function(p, cur, i) {
        (p[i/n|0] = p[i/n|0] || []).push(cur);
        return p;
    },[]);
}

chunk([1,2,3,4,5,6,7], 3);

这是一个带有尾递归和数组解构的版本。

远非最快的性能,但我只是觉得好笑,js现在可以做到这一点。即使它没有为此进行优化:(

const getChunks = (arr, chunk_size, acc = []) => {
    if (arr.length === 0) { return acc }
    const [hd, tl] = [ arr.slice(0, chunk_size), arr.slice(chunk_size) ]
    return getChunks(tl, chunk_size, acc.concat([hd]))
}

// USAGE
const my_arr = [1,2,3,4,5,6,7,8,9]
const chunks = getChunks(my_arr, 2)
console.log(chunks) // [[1,2],[3,4], [5,6], [7,8], [9]]