將一維陣列分割為 JavaScript 中的二維陣列
我們需要編寫一個函式,該函式將一維陣列作為第一個引數,將數字 n 作為第二個引數,我們必須在父陣列中建立 n 個子陣列(**如果可能),並將元素相應地分隔到這些子陣列中。
** 如果陣列包含 9 個元素,而我們要求建立 4 個子陣列,那麼在每個子陣列中分配 2 個元素會建立 5 個子陣列,而在每個子陣列中分配 3 個元素會建立 3 個子陣列,因此在這種情況下,我們必須退回到最近的較低級別(在本例中為 3),因為我們的要求是在一些特殊情況下在每個子陣列中分配相同數量的元素,但不包括最後一個。
例如 -
// if the input array is: const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']; // and the number is 2 //then the output should be: const output = [ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ];
讓我們編寫此函式的程式碼 -
示例
const arr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
const splitArray = (arr, rows) => {
const itemsPerRow = Math.ceil(arr.length / rows);
return arr.reduce((acc, val, ind) => {
const currentRow = Math.floor(ind / itemsPerRow);
if(!acc[currentRow]){
acc[currentRow] = [val];
}else{
acc[currentRow].push(val);
};
return acc;
}, []);
};
console.log(splitArray(arr, 2));輸出
控制檯中的輸出將為 -
[ [ 'A', 'B', 'C', 'D', 'E' ], [ 'F', 'G', 'H', 'I' ] ]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP