代码之家  ›  专栏  ›  技术社区  ›  Number16BusShelter

Node.js中的快速数组分块

  •  1
  • Number16BusShelter  · 技术社区  · 7 年前

    我正在处理长数据集的数组分块。我需要创建一个特定大小的块的新数组。目前,我使用这个解决方案,但它显示出糟糕的性能。

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

    我想找到一些更好的方法,知道如何足够快地完成它,以及为什么我的代码不能很好地执行。

    3 回复  |  直到 7 年前
        1
  •  3
  •   user5047085 user5047085    7 年前

    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 streams:

    const strm = new Writable({
      write(chunk, enc, cb){
         // do whatever
      }
    });
    
        2
  •  0
  •   Mohammed Essehemy    7 年前

    chunk 方法,这就是你需要的

    const _ = require('lodash');
    _.chunk([1,2,3,4,5,6],2);
    
        3
  •  0
  •   Akrion    7 年前

    const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
    const size = 5
    
    const chunkIt = (arr, size) => {
      let buckets = []
    
      // Just create the buckets/chunks storage
      for (let i = 1; i <= Math.ceil(arr.length / size); i++) {
        buckets.push([])
      }
    
      // Put in the buckets/storage by index access only
      for (let i = 0; i < arr.length; i++) {
        var arrIndex = Math.ceil((i + 1) / size) - 1
        buckets[arrIndex].push(arr[i])
      }
    
      return buckets;
    }
    
    console.log(chunkIt(arr, size))

    我做了一些基本的JS基准测试,它做得很好。我们的想法是预先创建bucket,因为该操作不应该那么昂贵,然后只需按索引推送。