【问题标题】:Split array into chunks将数组拆分成块
【发布时间】:2012-01-19 17:00:12
【问题描述】:

假设我有一个如下所示的 Javascript 数组:

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

什么方法适合将数组分块(拆分)成许多较小的数组,比如说最多 10 个元素?

【问题讨论】:

标签: javascript arrays split


【解决方案1】:

您可以使用 Array.prototype.reduce 函数在一行中完成此操作。

let arr = [1,2,3,4];
function chunk(arr, size)
{
    let result = arr.reduce((rows, key, index) => (index % size == 0 ? rows.push([key]) : rows[rows.length-1].push(key)) && rows, []);
    return result;
}
        
console.log(chunk(arr,2));

【讨论】:

    【解决方案2】:

    TypeScript 版本。演示的是 101 个随机 uid 分成 10 个组

    const idArrayLengthLimit = 10;
    const randomOneHundredOneIdArray = Array
        .from(Array(101).keys())
        .map(() => generateUid(5));
    
    function generateUid(length: number) {
      const uidString: string[] = [];
      const uidChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
      for (let i = 0; i < length; i++) {
        uidString
          .push(uidChars.charAt(Math.floor(Math.random() * uidChars.length)));
      }
      return uidString.join('');
    }
    
    for (let i = 0; i < randomOneHundredOneIdArray.length; i++) {
     if(i % idArrayLengthLimit === 0){
         const result = randomOneHundredOneIdArray
           .filter((_,id) => id >= i && id < i + idArrayLengthLimit);
        // Observe result
        console.log(result);
     }
    }
    

    【讨论】:

      【解决方案3】:

      const array = ['a', 'b', 'c', 'd', 'e'];
      const size = 2;
      const chunks = [];
      while (array.length) {
          chunks.push(array.splice(0, size));
      }
      console.log(chunks);

      【讨论】:

        【解决方案4】:

        示例 未更改的源数组
        并且一次制作所有的块。 (节省内存!)

        const array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
        
        const chunkSize = 4
        for (var i = 0; i < array.length; i += chunkSize) {
            const chunk = array.slice(i, i + chunkSize);
            console.log('chunk=',chunk)
            // do whatever
        }
        console.log('src array didnt changed. array=',array)
        

        【讨论】:

          【解决方案5】:

          js

          function splitToBulks(arr, bulkSize = 20) {
              const bulks = [];
              for (let i = 0; i < Math.ceil(arr.length / bulkSize); i++) {
                  bulks.push(arr.slice(i * bulkSize, (i + 1) * bulkSize));
              }
              return bulks;
          }
          
          console.log(splitToBulks([1, 2, 3, 4, 5, 6, 7], 3));

          打字稿

          function splitToBulks<T>(arr: T[], bulkSize: number = 20): T[][] {
              const bulks: T[][] = [];
              for (let i = 0; i < Math.ceil(arr.length / bulkSize); i++) {
                  bulks.push(arr.slice(i * bulkSize, (i + 1) * bulkSize));
              }
              return bulks;
          }
          

          【讨论】:

            【解决方案6】:

            这里有一个更具体的案例,有人可能会发现它很有价值。我还没有看到这里提到过。

            如果您不想要恒定/均匀的块大小,而是想要指定拆分数组的索引,该怎么办。在这种情况下,您可以使用:

            const splitArray = (array = [], splits = []) => {
              array = [...array]; // make shallow copy to avoid mutating original
              const chunks = []; // collect chunks
              for (const split of splits.reverse()) chunks.push(array.splice(split)); // go backwards through split indices and lop off end of array
              chunks.push(array); // add last remaining chunk (at beginning of array)
              return chunks.reverse(); // restore chunk order
            };
            

            然后:

            splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], [4, 6]) 
            // [ [1, 2, 3, 4] , [5, 6] , [7, 8, 9] ]
            

            请注意,如果你给它非升序/重复/负/非整数/等拆分索引,这会做一些有趣的事情。您可以为这些边缘情况添加检查(例如 Array.from(new Set(array)) 以进行重复数据删除。

            【讨论】:

              【解决方案7】:

              我尝试了一个递归函数……

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

              ...这很好而且很短,但对于 1,000 个元素,它似乎需要大约 256× @AymKdn’s answer 的长度,对于 10,000 个元素,需要 1,058× !

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2012-01-23
                • 2022-01-06
                • 2013-06-27
                • 1970-01-01
                相关资源
                最近更新 更多