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

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

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


当前回答

# 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 ' '

其他回答

这里是一个仅使用递归和slice()的非突变解决方案。

const splitToChunks = (arr, chunkSize, acc = []) => (
    arr.length > chunkSize ?
        splitToChunks(
            arr.slice(chunkSize),
            chunkSize,
            [...acc, arr.slice(0, chunkSize)]
        ) :
        [...acc, arr]
);

然后简单地像splitToChunks([1,2,3,4,5], 3)一样使用它来获得[[1,2,3],[4,5]]。

这里有一个小提琴供你尝试:https://jsfiddle.net/6wtrbx6k/2/

我认为这是ES6语法的一个很好的递归解决方案:

Const chunk =函数(数组,大小){ If (!array.length) { 返回[]; } Const head = array。片(0,大小); Const tail = array.slice(size); 返回[头,…块(尾巴,大小)]; }; 块console.log(((1、2、3),2));

一个有效的解决方案是通过indexChunk将解决方案与slice和push连接起来,解决方案被分割成块:

function splitChunks(sourceArray, chunkSize) { if(chunkSize <= 0) throw "chunkSize must be greater than 0"; let result = []; for (var i = 0; i < sourceArray.length; i += chunkSize) { result[i / chunkSize] = sourceArray.slice(i, i + chunkSize); } return result; } let ar1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]; console.log("Split in chunks with 4 size", splitChunks(ar1, 4)); console.log("Split in chunks with 7 size", splitChunks(ar1, 7));

试试这个:

var oldArray =[“香蕉”、“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”,“香蕉”,“橙色”,“柠檬”、“苹果”、“芒果”); var newArray = []; 而(oldArray.length) { 让start = 0; 让end = 10; newArray.push (oldArray。片(开始、结束)); oldArray。拼接(开始、结束); } console.log (newArray);

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

我最喜欢的一个是:

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))