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

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

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


当前回答

js

函数splitToBulks(arr, bulkSize = 20) { Const bulks = []; 对于(设I = 0;i < Math.ceil(arr。长度/ bulkSize);我+ +){ bulks.push(加勒比海盗。(i * bulkSize, (i + 1) * bulkSize)); } 返回散货; } 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;
}

其他回答

一个很好的函数是:

function chunk(arr,times){
    if(times===null){var times = 10} //Fallback for users wanting to use the default of ten
   var tempArray = Array() //Array to be populated with chunks
    for(i=0;i<arr.length/times;i++){
     tempArray[i] = Array() //Sub-Arrays        //Repeats for each chunk         
   for(j=0;j<times;j++){
        if(!(arr[i*times+j]===undefined)){tempArray[i][j] = arr[i*times+j]//Populate Sub-  Arrays with chunks
    }
     else{
       j = times //Stop loop
       i = arr.length/times //Stop loop
  }
    }
     }
   return tempArray //Return the populated and chunked array
   }

用法如下:

chunk(array,sizeOfChunks)

我对它做了注释,这样你就能理解发生了什么。

(格式有点不对,我在移动设备上编程)

超级晚,但我解决了一个类似的问题,使用.join("")的方法将数组转换为一个巨大的字符串,然后使用regex将.match(/.{1,7}/)它转换为最大长度为7的子字符串数组。

const arr = ['abc', 'def', 'gh', 'ijkl', 'm', 'nopq', 'rs', 'tuvwx', 'yz'];
const arrayOfSevens = arr.join("").match(/.{1,7}/g);
// ["abcdefg", "hijklmn", "opqrstu", "vwxyz"]

看看这个在速度测试中如何与其他方法进行比较会很有趣吗

老问题:新答案!事实上,我一直在想这个问题的答案,并让一个朋友改进了它!就是这样:

Array.prototype.chunk = function ( n ) {
    if ( !this.length ) {
        return [];
    }
    return [ this.slice( 0, n ) ].concat( this.slice(n).chunk(n) );
};

[1,2,3,4,5,6,7,8,9,0].chunk(3);
> [[1,2,3],[4,5,6],[7,8,9],[0]]

我稍微改变了BlazeMonger的使用jQuery对象..

var $list = $('li'),
    $listRows = [];


for (var i = 0, len = $list.length, chunk = 4, n = 0; i < len; i += chunk, n++) {
   $listRows[n] = $list.slice(i, i + chunk);
}

ES6传播功能#ohmy #ftw

Const chunk = (size, xs) => xs.reduce ( (segments, _, index) => 索引%大小=== 0 ? […段,x。Slice (index, index + size)] 段, [] ); console.log(块(3,(1,2,3,4,5,6,7,8)));