Skip to content

Commit a8e4919

Browse files
committed
add chunkArray function to array manipulation snippets
1 parent 3f3137a commit a8e4919

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

public/consolidated/javascript.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22
{
33
"name": "Array Manipulation",
44
"snippets": [
5+
{
6+
"title": "Chunk Array",
7+
"description": "Splits an array into chunks based on a number.",
8+
"author": "LuziferSenpai",
9+
"tags": [
10+
"array",
11+
"partition",
12+
"reduce"
13+
],
14+
"contributors": [],
15+
"code": "function chunkArray(array, chunkSize) {\n if (!Array.isArray(array)) {\n throw new TypeError('Expected an array as the first argument.');\n }\n if (typeof chunkSize !== 'number' || chunkSize <= 0) {\n throw new RangeError('Chunk size must be a positive number.');\n }\n\n return array.reduce((chunks, item, index) => {\n const chunkIndex = Math.floor(index / chunkSize);\n\n if (!chunks[chunkIndex]) {\n chunks[chunkIndex] = [];\n }\n\n chunks[chunkIndex].push(item);\n\n return chunks;\n }, []);\n}\n\n// Usage:\nconst data = [1, 2, 3, 4, 5, 6, 7, 8];\nconst chunked = chunkArray(data, 3); // Returns: [[1, 2, 3], [4, 5, 6], [7, 8]]\n"
16+
},
517
{
618
"title": "Partition Array",
719
"description": "Splits an array into two arrays based on a callback function.",
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
---
2+
title: Chunk Array
3+
description: Splits an array into chunks based on a number.
4+
author: LuziferSenpai
5+
tags: array,partition,reduce
6+
---
7+
8+
```js
9+
function chunkArray(array, chunkSize) {
10+
if (!Array.isArray(array)) {
11+
throw new TypeError('Expected an array as the first argument.');
12+
}
13+
if (typeof chunkSize !== 'number' || chunkSize <= 0) {
14+
throw new RangeError('Chunk size must be a positive number.');
15+
}
16+
17+
return array.reduce((chunks, item, index) => {
18+
const chunkIndex = Math.floor(index / chunkSize);
19+
20+
if (!chunks[chunkIndex]) {
21+
chunks[chunkIndex] = [];
22+
}
23+
24+
chunks[chunkIndex].push(item);
25+
26+
return chunks;
27+
}, []);
28+
}
29+
30+
// Usage:
31+
const data = [1, 2, 3, 4, 5, 6, 7, 8];
32+
const chunked = chunkArray(data, 3); // Returns: [[1, 2, 3], [4, 5, 6], [7, 8]]
33+
```

0 commit comments

Comments
 (0)