将一维数组分割为 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