让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
让我们说我有一个Javascript数组看起来如下:
["Element 1","Element 2","Element 3",...]; // with close to a hundred elements.
什么样的方法适合将数组分成许多更小的数组,假设最多有10个元素?
当前回答
这里是整洁和优化的实现chunk()函数。假设默认块大小为10。
var chunk = function(list, chunkSize) {
if (!list.length) {
return [];
}
if (typeof chunkSize === undefined) {
chunkSize = 10;
}
var i, j, t, chunks = [];
for (i = 0, j = list.length; i < j; i += chunkSize) {
t = list.slice(i, i + chunkSize);
chunks.push(t);
}
return chunks;
};
//calling function
var list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var chunks = chunk(list);
其他回答
这是一个带有尾递归和数组解构的版本。
远非最快的性能,但我只是觉得好笑,js现在可以做到这一点。即使它没有为此进行优化:(
const getChunks = (arr, chunk_size, acc = []) => {
if (arr.length === 0) { return acc }
const [hd, tl] = [ arr.slice(0, chunk_size), arr.slice(chunk_size) ]
return getChunks(tl, chunk_size, acc.concat([hd]))
}
// USAGE
const my_arr = [1,2,3,4,5,6,7,8,9]
const chunks = getChunks(my_arr, 2)
console.log(chunks) // [[1,2],[3,4], [5,6], [7,8], [9]]
使用来自lodash的chunk
lodash.chunk(arr,<size>).forEach(chunk=>{
console.log(chunk);
})
我推荐使用lodash。分块是其中一个有用的功能。 产品说明:
npm i --save lodash
在你的项目中包括:
import * as _ from 'lodash';
用法:
const arrayOfElements = ["Element 1","Element 2","Element 3", "Element 4", "Element 5","Element 6","Element 7","Element 8","Element 9","Element 10","Element 11","Element 12"]
const chunkedElements = _.chunk(arrayOfElements, 10)
你可以在这里找到我的样本: https://playcode.io/659171/
这个问题可能有很多解决方案。
我最喜欢的一个是:
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))
Const array = ['a', 'b', 'c', 'd', 'e']; Const size = 2; Const chunks = []; While (array.length) { chunks.push(数组。拼接(0,大小)); } console.log(块);