让我们说我有一个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个元素?
当前回答
我更喜欢使用拼接法而不是切片法。 这个解决方案使用数组长度和块大小来创建循环计数,然后循环遍历数组,在每个步骤中由于拼接而在每个操作后变得更小。
function chunk(array, size) {
let resultArray = [];
let chunkSize = array.length/size;
for(i=0; i<chunkSize; i++) {
resultArray.push(array.splice(0, size));
}
return console.log(resultArray);
}
chunk([1,2,3,4,5,6,7,8], 2);
如果不想改变原始数组,可以使用展开操作符克隆原始数组,然后使用该数组来解决问题。
let clonedArray = [...OriginalArray]
其他回答
好吧,让我们从一个相当严格的开始:
function chunk(arr, n) {
return arr.slice(0,(arr.length+n-1)/n|0).
map(function(c,i) { return arr.slice(n*i,n*i+n); });
}
它是这样使用的:
chunk([1,2,3,4,5,6,7], 2);
然后我们就有了这个紧密的减速器函数:
function chunker(p, c, i) {
(p[i/this|0] = p[i/this|0] || []).push(c);
return p;
}
它是这样使用的:
[1,2,3,4,5,6,7].reduce(chunker.bind(3),[]);
因为当我们将它绑定到一个数字时,小猫就死了,我们可以像这样手动curry:
// Fluent alternative API without prototype hacks.
function chunker(n) {
return function(p, c, i) {
(p[i/n|0] = p[i/n|0] || []).push(c);
return p;
};
}
它是这样使用的:
[1,2,3,4,5,6,7].reduce(chunker(3),[]);
然后是仍然非常紧凑的函数,它可以一次性完成所有操作:
function chunk(arr, n) {
return arr.reduce(function(p, cur, i) {
(p[i/n|0] = p[i/n|0] || []).push(cur);
return p;
},[]);
}
chunk([1,2,3,4,5,6,7], 3);
尽量避免搞乱原生原型,包括Array。原型,如果你不知道谁将使用你的代码(第三方、同事、你自己等)。
有一些方法可以安全地扩展原型(但不是在所有浏览器中),也有一些方法可以安全地使用从扩展原型创建的对象,但更好的经验法则是遵循最小意外原则,并完全避免这些做法。
如果你有时间,可以看看Andrew Dupont的JSConf 2011演讲,“Everything is allowed: Extending Built-ins”,关于这个话题的讨论。
但回到问题上来,虽然上面的解决方案是可行的,但它们过于复杂,需要不必要的计算开销。以下是我的解决方案:
function chunk (arr, len) {
var chunks = [],
i = 0,
n = arr.length;
while (i < n) {
chunks.push(arr.slice(i, i += len));
}
return chunks;
}
// Optionally, you can do the following to avoid cluttering the global namespace:
Array.chunk = chunk;
你可以使用这个ES6块函数,它很容易使用:
Const chunk = (array, size) => Array.from({长度:Math.ceil(数组。Length / size)}, (value, index) =>数组。切片(索引*大小,索引*大小+大小)); const itemsPerChunk = 3; const inputArray = [a, b, c, d, e, f, g的); const newArray = chunk(inputArray, itemsPerChunk); console.log (newArray.length);/ / 3, document . write (JSON.stringify (newArray));/ / [[' a ', ' b ', ' c '], [' d ', ' e ', ' f '], [g]]
这是我使用的,它可能不是超级快,但它是紧凑和简单:
让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
使用来自lodash的chunk
lodash.chunk(arr,<size>).forEach(chunk=>{
console.log(chunk);
})