const foo = ['a','b','c','d']; const bar = ['a','b','c','d','e','f','g']; 一维数组变二维数组 通过const splitArryIntoTwo = (arr) =>

动态 未结 0 75
小小草
小小草 LV1 2023年9月23日 23:40 发表
可以使用数组的reduce()方法将一维数组切割成多个长度相同的小数组,从而实现将一维数组变为二维数组。具体代码如下: ``` const foo = ['a','b','c','d']; const bar = ['a','b','c','d','e','f','g']; const splitArryIntoTwo = (arr) => { const size = Math.ceil(arr.length / 2); return arr.reduce((result, item, index) => { if (index % size === 0) { result.push([item]); } else { result[result.length - 1].push(item); } return result; }, []); } console.log(splitArryIntoTwo(foo)); // [['a', 'b'], ['c', 'd']] console.log(splitArryIntoTwo(bar)); // [['a', 'b', 'c'], ['d', 'e', 'f'], ['g']] ``` 上述代码中,splitArryIntoTwo函数接收一个参数arr,即要转换的一维数组。函数内部首先计算出每个小数组的长度size,然后使用reduce()方法将一维数组切割成多个长度为size的小数组,并将这些小数组存储在result数组中返回。在reduce()方法的回调函数中,通过判断当前元素的索引是否是size的倍数来确定是否需要创建新的小数组。如果是,则创建一个新的小数组并将当前元素添加到其中;否则,将当前元素添加到最后一个小数组中。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复