假设我有一个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个元素?
const splitEvery = (n, xs, y=[]) =>
xs.length===0 ? y : splitEvery(n, xs.slice(n), y.concat([xs.slice(0, n)]))
console.log(splitEvery(2, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
in coffeescript:
b = (a.splice(0, len) while a.length)
demo
a = [1, 2, 3, 4, 5, 6, 7]
b = (a.splice(0, 2) while a.length)
[ [ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ],
[ 7 ] ]
如果您正在使用Underscore JS,请使用:
var result = _.chunk(arr,elements_per_chunk)
大多数项目无论如何都已经使用underscore作为依赖。
ES6扩展函数式编程 #ohmy #ftw
const chunk =
(size, xs) =>
xs.reduce(
(segments, _, index) =>
index % size === 0
? [...segments, xs.slice(index, index + size)]
: segments,
[]
);
console.log( chunk(3, [1, 2, 3, 4, 5, 6, 7, 8]) );
对于一个功能性的解决方案,使用Ramda:
其中popularProducts
是您的输入数组,5
是块大小。
import splitEvery from 'ramda/src/splitEvery'
splitEvery(5, popularProducts).map((chunk, i) => {
// do something with chunk
})
ES6 生成器版本
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);
const
。 - Константин Ван当源数组发生变化时:
let a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], aa = [], x
while((x = a.splice(0, 2)).length) aa.push(x)
// aa == [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ]
// a == []
不改变原始数组的情况下:
let a = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], aa = []
for(let i = 0; i < a.length; i += 2) aa.push(a.slice(i, i + 2))
// aa == [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ], [ 9 ] ]
// a == [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
let chunksplit = (stream, size) => stream.reduce((chunks, item, idx, arr) => (idx % size == 0) ? [...chunks, arr.slice(idx, idx + size)] : chunks, []);
//if the index is a multiple of the chunksize, add new array
let 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) ));
//using JSON.stringify for the nested arrays to be shown
const arr = '1234567890'.split('');
const chunkSize = 3;
const r = arr.reduce((arr, item, idx) => (arr[idx / chunkSize | 0] ??= []).push(item) && arr, []);
console.log(JSON.stringify(r));
基于Array.prototype
reduce
和 push
方法的ES6一行代码实现:
const doChunk = (list, size) => list.reduce((r, v) =>
(!r.length || r[r.length - 1].length === size ?
r.push([v]) : r[r.length - 1].push(v)) && r
, []);
console.log(doChunk([0,1,2,3,4,5,6,7,8,9,10,11,12], 5));
// [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12]]