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

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

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


当前回答

在JS,

const splitInChunks = (arr,n) => {
  let chunksArr = [];
  if(arr !=null && arr!= undefined){
      for(i=0; i<arr.length;i+=n){
      if(arr.length-i>=n)
          chunksArr.push(arr.slice(i,i+n))
      else
           chunksArr.push(arr.slice(i,arr.length))
  }
  return chunksArr
  }
}

其他回答

一个很好的函数是:

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)

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

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

我的技巧是使用parseInt(i/chunkSize)和parseInt(i%chunkSize),然后填充数组

// filling items let array = []; for(let i = 0; i< 543; i++) array.push(i); // printing the splitted array console.log(getSplittedArray(array, 50)); // get the splitted array function getSplittedArray(array, chunkSize){ let chunkedArray = []; for(let i = 0; i<array.length; i++){ try{ chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i]; }catch(e){ chunkedArray[parseInt(i/chunkSize)] = []; chunkedArray[parseInt(i/chunkSize)][parseInt(i%chunkSize)] = array[i]; } } return chunkedArray; }

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

如果你不想要固定/均匀的数据块大小,而是想要指定拆分数组的下标怎么办?在这种情况下,你可以使用这个:

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))来消除重复。

ES6 Generator版本

function* chunkArray(array,size=1){
    var clone = array.slice(0);
    while (clone.length>0) 
      yield clone.splice(0,size); 
};
var a = new Array(100).fill().map((x,index)=>index);
for(const c of chunkArray(a,10)) 
    console.log(c);

这是我使用的,它可能不是超级快,但它是紧凑和简单:

让chunksplit = (stream, size) => stream。Reduce ((chunk, item, idx, arr) => (idx % size == 0) ?[…块,加勒比海盗。Slice (idx, idx + size)]: chunk, []); //如果索引是chunksize的倍数,则添加新数组 让testArray =[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12日,13日,14日,15日,16日,17日,18日,19日,20日,21日,22日); document . write (JSON。stringify(chunksplit(testArray, 5)); / /使用JSON。要显示的嵌套数组的Stringify