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

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

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


当前回答

她是一个简单的解决方案使用@Blazemonger解决方案

function array_chunk(arr, size){
    // initialize vars
    var i,
    j = arr.length,
    tempArray = [];
    // loop through and jump based on size
    for (i=0; i<j; i+=size) {
        // slice chunk of arr and push to tempArray
        tempArray.push(arr.slice(i,i+size));
    }
    // return temp array (chunck)
    return tempArray
}

这让我的管道流动起来,希望这能帮助到其他人。:)

其他回答

最有效的方法是将数组视为Iterable,并进行惰性分页。这样,它将只在请求时生成数据。下面的代码使用了iter-ops库中的操作符页:

import {pipe, page} from 'iter-ops';

const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // some input data

const i = pipe(arr, page(2)); //=> Iterable<number>

console.log(...i); //=> [ 1, 2 ] [ 3, 4 ] [ 5, 6 ] [ 7, 8 ] [ 9 ]

工作方式与任何Iterable或AsyncIterable相同。


附:我是图书馆的作者。

这是我能想到的最有效、最直接的解决方案:

function chunk(array, chunkSize) {
    let chunkCount = Math.ceil(array.length / chunkSize);
    let chunks = new Array(chunkCount);
    for(let i = 0, j = 0, k = chunkSize; i < chunkCount; ++i) {
        chunks[i] = array.slice(j, k);
        j = k;
        k += chunkSize;
    }
    return chunks;
}

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

远非最快的性能,但我只是觉得好笑,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]]

我的目标是在纯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中荒谬的弱数组函数可以制作出很好的谜题:-)

使用ES6的拼接版本

让[列表,chunkSize] =[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12、13、14、15),6]; list =[…数组(Math.ceil(list. ceil))length / chunkSize))]。map(_ => list.splice(0,chunkSize)) console.log(列表);