让我们说我有一个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个元素?
当前回答
当前排名靠前的答案存在的问题是,它们产生了不平衡的数据块。例如,当前接受的答案将把一个101个元素的数组分布为10个大小为10的块,后面是一个大小为1的块。
使用一些模块化算法可以创建统一的块大小,差异永远不会超过1:
函数split_array(a, nparts) { const quot = Math.floor;长度/ nparts) Const rem = a.length % nparts Var部件= [] For (var I = 0;I < nparts;+ + i) { const begin = i * quot +数学。分钟(rem,我) Const end = begin + quot + (i < rem) parts.push (a。片(开始、结束) } 返回部分 } Var chunk = split_array([1,2,3,4,5,6,7,8,9,10], 3) console.log (JSON.stringify(块)
输出:
[[1,2,3,4],[5,6,7],[8,9,10]]
(摘自相关答案)
其他回答
使用Array.prototype.reduce()的另一个解决方案:
Const chunk = (array, size) => 数组中。Reduce ((acc, _, i) => { If (i % size === 0) ac .push(数组。切片(i, i + size)) 返回acc }, []) / /使用方法: Const数= [1,2,3,4,5,6,7,8,9,10] Const chunked = chunk(number, 3) console.log(分块)
这个解决方案与Steve Holgado的解决方案非常相似。但是,因为这个解决方案没有利用数组扩展,也没有在reducer函数中创建新数组,所以它比其他解决方案更快(参见jsPerf test),而且主观上更可读(语法更简单)。
在每n次迭代(其中n = size;从第一次迭代开始),累加器数组(acc)附加了数组的一个块(array。Slice (i, i + size)),然后返回。在其他迭代中,累加器数组按原样返回。
如果size为零,该方法返回一个空数组。如果size为负,则该方法返回破碎的结果。因此,如果在您的情况下需要,您可能需要对负的或非正的大小值进行处理。
如果在你的情况下速度很重要,一个简单的for循环将比使用reduce()更快(参见jsPerf测试),一些人可能会发现这种风格更易于阅读:
function chunk(array, size) {
// This prevents infinite loops
if (size < 1) throw new Error('Size must be positive')
const result = []
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size))
}
return result
}
最有效的方法是将数组视为Iterable,并进行惰性分页。这样,它将只在请求时生成数据。下面的代码使用了iter-ops库中的操作符页:
import {pipe, page} from 'iter-ops';
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; // some input data
const i = pipe(arr, page(2)); //=> Iterable<number>
console.log(...i); //=> [ 1, 2 ] [ 3, 4 ] [ 5, 6 ] [ 7, 8 ] [ 9 ]
工作方式与任何Iterable或AsyncIterable相同。
附:我是图书馆的作者。
这是一个递归的解决方案,尾部调用优化。
const splitEvery = (n, xs, y=[]) => xs。长度= = = 0 ?y: splitEvery(n, xs.slice(n), y.concat([xs. slice(n)])片(0,n)))) console.log(splitEvery(2, [0,1,2,3,4,5,6,7,8,9]))
ES6传播功能#ohmy #ftw
Const chunk = (size, xs) => xs.reduce ( (segments, _, index) => 索引%大小=== 0 ? […段,x。Slice (index, index + size)] 段, [] ); console.log(块(3,(1,2,3,4,5,6,7,8)));
我认为这是ES6语法的一个很好的递归解决方案:
Const chunk =函数(数组,大小){ If (!array.length) { 返回[]; } Const head = array。片(0,大小); Const tail = array.slice(size); 返回[头,…块(尾巴,大小)]; }; 块console.log(((1、2、3),2));