UNPKG

1.06 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3// This is supposed to be a faster concat...
4// https://dev.to/uilicious/javascript-array-push-is-945x-faster-than-array-concat-1oki
5
6/**
7 * @name arrayFlatten
8 * @summary Merge T[][] into T[]
9 * @description
10 * Returns a new array with all arrays merged into one
11 * @example
12 * <BR>
13 *
14 * ```javascript
15 * import { arrayFlatten } from '@polkadot/util';
16 *
17 * arrayFlatten([[1, 2], [3, 4], [5]]); // [1, 2, 3, 4, 5]
18 * ```
19 */
20export function arrayFlatten(arrays) {
21 // noop for the single-entry case
22 if (arrays.length === 1) {
23 return arrays[0];
24 } // pre-allocate based on the combined size
25
26
27 let size = 0;
28
29 for (let i = 0; i < arrays.length; i++) {
30 size += arrays[i].length;
31 }
32
33 const output = new Array(size);
34 let i = -1;
35
36 for (let j = 0; j < arrays.length; j++) {
37 const a = arrays[j]; // instead of pushing, we just set the entries
38
39 for (let e = 0; e < a.length; e++) {
40 output[++i] = a[e];
41 }
42 }
43
44 return output;
45}
\No newline at end of file