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

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

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


当前回答

这个问题可能有很多解决方案。

我最喜欢的一个是:

function chunk(array, size) { const chunked = []; for (element of array){ let last = chunked[chunked.length - 1]; if(last && last.length != size){ last.push(element) }else{ chunked.push([element]) } } return chunked; } function chunk1(array, size) { const chunked = []; let index = 0; while(index < array.length){ chunked.push(array.slice(index,index+ size)) index += size; } return chunked; } console.log('chunk without slice:',chunk([1,2,3,4,5,5],2)); console.log('chunk with use of slice funtion',chunk1([1,2,3,4,5,6],2))

其他回答

使用发电机

函数*块(arr, n) { 对于(设I = 0;I < arrr .length;I += n) { 加勒比海盗。Slice (i, i + n); } } let someArray = [0,1,2,3,4,5,6,7,8,9] console.log([…块(someArray, 2)]) / /[[0, 1],[2、3],[4,5],[6、7],[8 9]]

可以像这样用Typescript输入:

function* chunks<T>(arr: T[], n: number): Generator<T[], void> {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n);
  }
}
# in coffeescript
# assume "ar" is the original array
# newAr is the new array of arrays

newAr = []
chunk = 10
for i in [0... ar.length] by chunk
   newAr.push ar[i... i+chunk]

# or, print out the elements one line per chunk
for i in [0... ar.length] by chunk
   console.log ar[i... i+chunk].join ' '

array.slice()方法可以根据需要从数组的开头、中间或结尾提取切片,而不需要改变原始数组。

const chunkSize = 10;
for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    // do whatever
}

最后一个块可能小于chunkSize。例如,当给定一个包含12个元素的数组时,第一个块将有10个元素,第二个块只有2个。

注意,chunkSize为0将导致无限循环。

一个很好的函数是:

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)

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

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

我只是在groupBy函数的帮助下写了这个。

// utils const group = (source) => ({ by: (grouping) => { const groups = source.reduce((accumulator, item) => { const name = JSON.stringify(grouping(item)); accumulator[name] = accumulator[name] || []; accumulator[name].push(item); return accumulator; }, {}); return Object.keys(groups).map(key => groups[key]); } }); const chunk = (source, size) => group(source.map((item, index) => ({ item, index }))) .by(x => Math.floor(x.index / size)) .map(x => x.map(v => v.item)); // 103 items const arr = [6,2,6,6,0,7,4,9,3,1,9,6,1,2,7,8,3,3,4,6,8,7,6,9,3,6,3,5,0,9,3,7,0,4,1,9,7,5,7,4,3,4,8,9,0,5,1,0,0,8,0,5,8,3,2,5,6,9,0,0,1,5,1,7,0,6,1,6,8,4,9,8,9,1,6,5,4,9,1,6,6,1,8,3,5,5,7,0,8,3,1,7,1,1,7,6,4,9,7,0,5,1,0]; const chunks = chunk(arr, 10); console.log(JSON.stringify(chunks));