2677.分块数组
链接:2677.分块数组
难度:Easy
标签:
简介:给定一个数组 arr 和一个块大小 size ,返回一个 分块 的数组。分块 的数组包含了 arr 中的原始元素,但是每个子数组的长度都是 size 。如果 arr.length 不能被 size 整除,那么最后一个子数组的长度可能小于 size 。
题解 1 - typescript
- 编辑时间:2023-05-16
- 执行用时:76ms
- 内存消耗:45.5MB
- 编程语言:typescript
- 解法介绍:利用余数为0判断是否产生分割。
function chunk(arr: any[], size: number): any[][] {
const res: any[][] = [];
const item: any[] = [];
for (let i = 1; i <= arr.length; i++) {
item.push(arr[i - 1]);
if (i % size === 0) res.push([...item]), (item.length = 0);
}
if (item.length) res.push([...item]);
return res;
}