一个数组包含很多项目,我想把它分成多块。
我想出了两个完全不同的解决方案。
A) 第一种是将数组分成相等的小块,例如2个或3个项目的小块 B) 第二种是创建n个小块,并在其中添加一个相等的可变项目集
我们划分的方式和原因是不同的。当你不知道最终会有多少个组,也不在乎,但你知道你在每个新创建的数组中要有X个项目时,解决方案(A)很好
解决方案(B)是很好的,当你知道你要创建多少个组,而且你对这个问题很严格,但不关心每个新数组将包含多少项。
换句话说,对于一个像
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
使用解决方案(A),我们可以创建2个项目的块,并得到
[ 1, 2 ]
[ 3, 4 ]
[ 5, 6 ]
[ 7, 8 ]
[ 9, 10 ]
或3个项目的块。
[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]
[ 10 ]
用解决方案(B),我们可以把数组分成2个数组,然后得到。
[ 1, 2, 3, 4, 5 ]
[ 6, 7, 8, 9, 10 ]
或者我们可以把数组分成3个数组,然后得到。
[ 1, 2, 3, 4 ]
[ 4, 5, 6, 7]
[ 8, 9, 10 ]
下面是(A)的实现。
const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] //… your array, filled with values
const n = 3 //tweak this to add more items per line
const result = new Array(Math.ceil(items.length / n))
.fill()
.map(_ => items.splice(0, n))
在这个例子中result ,是一个新的数组的数组。
[ [ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
[ 10 ]
]
请注意,原始数组被修改,使用
splice()
下面是(B)的实现,假设你想要一个由3个数组组成的数组作为结果。
const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] //… your array, filled with values
const n = 3
const result = [[], [], []] //we create it, then we'll fill it
const wordsPerLine = Math.ceil(items.length / 3)
for (let line = 0; line < n; line++) {
for (let i = 0; i < wordsPerLine; i++) {
const value = items[i + line * wordsPerLine]
if (!value) continue //avoid adding "undefined" values
result[line].push(value)
}
}
在这个例子中result 是
[ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10 ]
]