首页 > 解决方案 > Node.js 中的快速数组分块

问题描述

我正在处理长数据集的数组分块。我需要创建一个新的一定大小的块数组。目前,我使用这个解决方案,但它表现不佳。

function array_to_chunks(data, size){
   let chunks = []
   let d = data.slice()
   while (d.length >= size) chunks.push(d.splice(0, size))
   return chunks
}

我想找到一些关于如何足够快地完成它以及为什么我的代码表现不佳的更好的想法。

标签: javascriptarraysnode.jschunksarray-splice

解决方案


这稍微提高了性能,因为您不必复制数组:

const createGroupedArray = function (arr, chunkSize) {

    if (!Number.isInteger(chunkSize)) {
        throw 'Chunk size must be an integer.';
    }

    if (chunkSize < 1) {
        throw 'Chunk size must be greater than 0.';
    }

    const groups = [];
    let i = 0;
    while (i < arr.length) {
        groups.push(arr.slice(i, i += chunkSize));
    }
    return groups;
};

如果您正在执行 I/O,则使用 Node.js 流:

const strm = new Writable({
  write(chunk, enc, cb){
     // do whatever
  }
});

推荐阅读