[Algorithm] Chunk Array
2024-08-31 15:04:14
// --- Directions
// Given an array and chunk size, divide the array into many subarrays
// where each subarray is of length size
// --- Examples
// chunk([1, 2, 3, 4], 2) --> [[ 1, 2], [3, 4]]
// chunk([1, 2, 3, 4, 5], 2) --> [[ 1, 2], [3, 4], [5]]
// chunk([1, 2, 3, 4, 5, 6, 7, 8], 3) --> [[ 1, 2, 3], [4, 5, 6], [7, 8]]
// chunk([1, 2, 3, 4, 5], 4) --> [[ 1, 2, 3, 4], [5]]
// chunk([1, 2, 3, 4, 5], 10) --> [[ 1, 2, 3, 4, 5]]
function chunk(array, size) {
let result = [];
let temp = [];
const len = array.length;
for (let i = 0; i < len; i++) {
let mod = i % size;
if (mod === 0) {
if (temp.length !== 0) {
result = [...result, temp];
}
temp = [];
} temp[mod] = array[i];
} result = [...result, temp]; return result;
}
way 2:
function chunk(array, size) {
let chunked = [];
let index = 0; while (index < array.length) {
chunked.push(array.slice(index, index + size));
index += size;
} return chunked;
}
test:
const chunk = require("./index"); test("function chunk exists", () => {
expect(typeof chunk).toEqual("function");
}); test("chunk divides an array of 10 elements with chunk size 2", () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const chunked = chunk(arr, 2); expect(chunked).toEqual([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]);
}); test("chunk divides an array of 3 elements with chunk size 1", () => {
const arr = [1, 2, 3];
const chunked = chunk(arr, 1); expect(chunked).toEqual([[1], [2], [3]]);
}); test("chunk divides an array of 5 elements with chunk size 3", () => {
const arr = [1, 2, 3, 4, 5];
const chunked = chunk(arr, 3); expect(chunked).toEqual([[1, 2, 3], [4, 5]]);
}); test("chunk divides an array of 13 elements with chunk size 5", () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const chunked = chunk(arr, 5); expect(chunked).toEqual([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13]]);
});
最新文章
- ok
- C#对七牛云的操作
- Java设计模式(七) 模板模式
- 从Sql server 2008获取表字段属性信息,注释信息
- windows系统调用 利用事件对象实现进程通信
- 实现快速迭代的引擎设计 - Capcom RE Engine的架构与实现
- c# params
- 【锋利的JQuery-学习笔记】添加提示图片
- 关于ref与out的区别
- Git客户端使用
- mysql基础: mysql列类型--字符串
- 字符转十六进制 String =>; HEX using ";hexdump"; on linux
- Chapter 2 Open Book&mdash;&mdash;13
- java.text.DateFormat 多线程并发问题
- centos7安装Jenkins更改默认端口并配置Ldap服务器进行用户认证
- 项目复审——Beta阶段
- VSCode集成TypeScript编译
- 用localStorage来存储数据的一些经验
- linux pmap命令
- 怎样绕开QQ通讯录和360的广播中断
热门文章
- java获取单张网页中img标签中的src
- Netty的学习
- class CAdoInterface
- 剑指offer49:把字符串转换成整数
- PHP内存管理-zendMM
- 对Python中print函数参数的认识
- Docker pull 出现的 error pulling image configuration: Get https://dseasb33srnrn.cloudfront.net/
- 贝叶斯优化 Bayesian Optimization
- Java Web-servlet、HTTP in servlet和捎带的Java绘图学习
- HTML给标题栏添加图标