如何在JS中將數組劃分為多個相等的部分

我有一個問題。

數組包含很多項目,我想將其分為多個塊。

我想出了2種完全不同的解決方案。

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 ]

or chunks of 3 items:

[ 1, 2, 3 ]
[ 4, 5, 6 ]
[ 7, 8, 9 ]
[ 10 ]

With solution (B) we can divide the array in 2 arrays, and get:

[ 1, 2, 3, 4, 5 ]
[ 6, 7, 8, 9, 10 ]

Or we can divide the array in 3 arrays, and get:

[ 1, 2, 3, 4 ]
[ 4, 5, 6, 7]
[ 8, 9, 10 ]

Here is the implementation of (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))

In this example result is a new array of arrays:

[ 
  [ 1, 2, 3 ], 
  [ 4, 5, 6 ], 
  [ 7, 8, 9 ], 
  [ 10 ] 
]

Here is the implementation of (B), assuming you want an array of 3 arrays as a result:

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) } }

In this example result is

[ 
  [ 1, 2, 3, 4 ], 
  [ 5, 6, 7, 8 ], 
  [ 9, 10 ] 
]  

More js tutorials: