0
# Array Utilities
1
2
Functional array manipulation utilities for common operations like chunking, flattening, shuffling, and data transformation in JavaScript/TypeScript applications.
3
4
## Capabilities
5
6
### Array Transformation
7
8
Core array manipulation functions for transforming array structures.
9
10
```typescript { .api }
11
/**
12
* Splits an array into chunks of specified size
13
* @param array - Array to split into chunks
14
* @param size - Size of each chunk
15
*/
16
function arrayChunk<T>(array: T[], size: number): T[][];
17
18
/**
19
* Flattens a multi-dimensional array into a single dimension
20
* @param array - Array containing nested arrays or single values
21
*/
22
function arrayFlatten<T>(array: (T | T[])[]): T[];
23
24
/**
25
* Creates an array of numbers within a specified range
26
* @param size - Number of elements to generate
27
* @param startAt - Starting number (default: 0)
28
*/
29
function arrayRange(size: number, startAt?: number): number[];
30
31
/**
32
* Randomly shuffles the elements of an array
33
* @param array - Array to shuffle
34
*/
35
function arrayShuffle<T>(array: T[]): T[];
36
```
37
38
### Array Combination
39
40
Functions for combining and manipulating multiple arrays.
41
42
```typescript { .api }
43
/**
44
* Zips/combines multiple arrays into tuples
45
* @param arrays - Arrays to zip together
46
*/
47
function arrayZip<T>(...arrays: T[][]): T[][];
48
49
/**
50
* Unzips/transposes an array of arrays
51
* @param array - Array of arrays to unzip
52
*/
53
function arrayUnzip<T>(array: T[][]): T[][];
54
```
55
56
### Array Filtering
57
58
Advanced filtering utilities for arrays.
59
60
```typescript { .api }
61
/**
62
* Filters an array based on a predicate function
63
* @param array - Array to filter
64
* @param fn - Predicate function returning boolean
65
*/
66
function arrayFilter<T>(array: T[], fn: (value: T, index: number, array: T[]) => boolean): T[];
67
```
68
69
## Usage Examples
70
71
**Array Chunking:**
72
73
```typescript
74
import { arrayChunk } from "@polkadot/util";
75
76
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
77
const chunks = arrayChunk(numbers, 3);
78
console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
79
80
// Processing data in batches
81
const items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
82
const batches = arrayChunk(items, 2);
83
// Process each batch separately
84
batches.forEach((batch, index) => {
85
console.log(`Batch ${index + 1}:`, batch);
86
});
87
```
88
89
**Array Flattening:**
90
91
```typescript
92
import { arrayFlatten } from "@polkadot/util";
93
94
const nested = [1, [2, 3], 4, [5, [6, 7]], 8];
95
const flat = arrayFlatten(nested);
96
console.log(flat); // [1, 2, 3, 4, 5, [6, 7], 8] (one level deep)
97
98
// Flattening mixed data
99
const mixed = ['hello', ['world', 'foo'], 'bar'];
100
const flattened = arrayFlatten(mixed);
101
console.log(flattened); // ['hello', 'world', 'foo', 'bar']
102
```
103
104
**Range Generation:**
105
106
```typescript
107
import { arrayRange } from "@polkadot/util";
108
109
// Generate 0-based range
110
const zeroToFour = arrayRange(5);
111
console.log(zeroToFour); // [0, 1, 2, 3, 4]
112
113
// Generate custom start range
114
const fiveToNine = arrayRange(5, 5);
115
console.log(fiveToNine); // [5, 6, 7, 8, 9]
116
117
// Generate indices for iteration
118
const indices = arrayRange(10, 1); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
119
```
120
121
**Array Shuffling:**
122
123
```typescript
124
import { arrayShuffle } from "@polkadot/util";
125
126
const cards = ['A', 'K', 'Q', 'J', '10', '9', '8', '7'];
127
const shuffled = arrayShuffle([...cards]); // Creates new shuffled array
128
console.log(shuffled); // Random order: ['Q', '7', 'A', 'J', ...]
129
130
// Shuffle while preserving original
131
const original = [1, 2, 3, 4, 5];
132
const randomized = arrayShuffle([...original]);
133
console.log('Original:', original); // [1, 2, 3, 4, 5]
134
console.log('Shuffled:', randomized); // [3, 1, 5, 2, 4] (random)
135
```
136
137
**Array Zipping:**
138
139
```typescript
140
import { arrayZip } from "@polkadot/util";
141
142
const names = ['Alice', 'Bob', 'Charlie'];
143
const ages = [25, 30, 35];
144
const cities = ['NYC', 'LA', 'Chicago'];
145
146
const combined = arrayZip(names, ages, cities);
147
console.log(combined);
148
// [
149
// ['Alice', 25, 'NYC'],
150
// ['Bob', 30, 'LA'],
151
// ['Charlie', 35, 'Chicago']
152
// ]
153
154
// Creating key-value pairs
155
const keys = ['name', 'age', 'active'];
156
const values = ['John', 28, true];
157
const pairs = arrayZip(keys, values);
158
console.log(pairs); // [['name', 'John'], ['age', 28], ['active', true]]
159
```
160
161
**Array Unzipping:**
162
163
```typescript
164
import { arrayUnzip } from "@polkadot/util";
165
166
const tuples = [
167
['Alice', 25, 'NYC'],
168
['Bob', 30, 'LA'],
169
['Charlie', 35, 'Chicago']
170
];
171
172
const [names, ages, cities] = arrayUnzip(tuples);
173
console.log(names); // ['Alice', 'Bob', 'Charlie']
174
console.log(ages); // [25, 30, 35]
175
console.log(cities); // ['NYC', 'LA', 'Chicago']
176
```
177
178
**Advanced Filtering:**
179
180
```typescript
181
import { arrayFilter } from "@polkadot/util";
182
183
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
184
185
// Filter even numbers
186
const evens = arrayFilter(numbers, (n) => n % 2 === 0);
187
console.log(evens); // [2, 4, 6, 8, 10]
188
189
// Filter with index
190
const skipFirst = arrayFilter(numbers, (value, index) => index > 0);
191
console.log(skipFirst); // [2, 3, 4, 5, 6, 7, 8, 9, 10]
192
193
// Complex filtering
194
const users = [
195
{ name: 'Alice', age: 25, active: true },
196
{ name: 'Bob', age: 17, active: false },
197
{ name: 'Charlie', age: 30, active: true }
198
];
199
200
const activeAdults = arrayFilter(users, (user) => user.active && user.age >= 18);
201
console.log(activeAdults); // [{ name: 'Alice', age: 25, active: true }, ...]
202
```
203
204
**Combining Multiple Array Operations:**
205
206
```typescript
207
import { arrayRange, arrayChunk, arrayShuffle, arrayZip } from "@polkadot/util";
208
209
// Create shuffled pairs for a tournament
210
function createTournamentPairs(playerCount: number) {
211
// Generate player numbers
212
const players = arrayRange(playerCount, 1); // [1, 2, 3, ..., playerCount]
213
214
// Shuffle for random matchups
215
const shuffled = arrayShuffle(players);
216
217
// Group into pairs
218
const pairs = arrayChunk(shuffled, 2);
219
220
// Create match objects
221
return pairs.map((pair, index) => ({
222
match: index + 1,
223
player1: pair[0],
224
player2: pair[1] || null // Handle odd number of players
225
}));
226
}
227
228
const tournament = createTournamentPairs(8);
229
console.log(tournament);
230
// [
231
// { match: 1, player1: 5, player2: 2 },
232
// { match: 2, player1: 7, player2: 1 },
233
// { match: 3, player1: 3, player2: 8 },
234
// { match: 4, player1: 6, player2: 4 }
235
// ]
236
```