UNPKG

960 BJavaScriptView Raw
1/**
2 * @name arrayFlatten
3 * @summary Merge T[][] into T[]
4 * @description
5 * Returns a new array with all arrays merged into one
6 * @example
7 * <BR>
8 *
9 * ```javascript
10 * import { arrayFlatten } from '@polkadot/util';
11 *
12 * arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
13 * ```
14 */
15export function arrayFlatten(arrays) {
16 const num = arrays.length;
17 // shortcuts for the empty & single-entry case
18 if (num === 0) {
19 return [];
20 }
21 else if (num === 1) {
22 return arrays[0];
23 }
24 // pre-allocate based on the combined size
25 let size = 0;
26 for (let i = 0; i < num; i++) {
27 size += arrays[i].length;
28 }
29 const output = new Array(size);
30 let i = -1;
31 for (let j = 0; j < num; j++) {
32 const a = arrays[j];
33 // instead of pushing, we just set the entries
34 for (let e = 0, count = a.length; e < count; e++) {
35 output[++i] = a[e];
36 }
37 }
38 return output;
39}