@kevinwin/

flattenArray

Nodejs

No description

fork
loading
Files
  • index.js

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.9956737925432948","path":"index.js","file":{"path":"index.js","content":{"asEncoding":{"base64":"ZnVuY3Rpb24gcmVjdXJzaXZlRmxhdHRlbihhcnJheSkgewogIHJldHVybiBhcnJheS5yZWR1Y2UoKGFjY3VtdWxhdG9yLCBlbGVtZW50KSA9PiB7CiAgICByZXR1cm4gQXJyYXkuaXNBcnJheShlbGVtZW50KSA/IFsuLi5hY2N1bXVsYXRvciwgLi4ucmVjdXJzaXZlRmxhdHRlbihlbGVtZW50KV0gOiBbLi4uYWNjdW11bGF0b3IsIGVsZW1lbnRdOyAvLyBNZXJnaW5nIHRoZSB0d28gY29tcG9uZW50cyBjYW4gYWxzbyBoYXBwZW4gd2l0aCAuY29uY2F0CiAgfSwgW10pOwp9CgpmdW5jdGlvbiBpdGVyYXRpdmVGbGF0dGVuKGFycmF5KSB7CiAgICBjb25zdCBzdGFjayA9IFsuLi5hcnJheV07CiAgICBjb25zdCByZXN1bHQgPSBbXTsKICAgIAogICAgd2hpbGUgKHN0YWNrLmxlbmd0aCkgewogICAgICAgIGNvbnN0IG5leHQgPSBzdGFjay5wb3AoKTsKICAgICAgICAKICAgICAgICBpZiAoQXJyYXkuaXNBcnJheShuZXh0KSkgewogICAgICAgICAgICBzdGFjay5wdXNoKC4uLm5leHQpOwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIHJlc3VsdC5wdXNoKG5leHQpOwogICAgICAgIH0KICAgIH0KICAgIAogICAgcmV0dXJuIHJlc3VsdC5yZXZlcnNlKCk7Cn0="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function recursiveFlatten(array) {
  return array.reduce((accumulator, element) => {
    return Array.isArray(element) ? [...accumulator, ...recursiveFlatten(element)] : [...accumulator, element]; // Merging the two components can also happen with .concat
  }, []);
}

function iterativeFlatten(array) {
    const stack = [...array];
    const result = [];
    
    while (stack.length) {
        const next = stack.pop();
        
        if (Array.isArray(next)) {
            stack.push(...next);
        } else {
            result.push(next);
        }
    }
    
    return result.reverse();
}
node v10.16.0