Skip to content

Instantly share code, notes, and snippets.

@mariuszklinger
Last active January 29, 2020 11:15
Show Gist options
  • Save mariuszklinger/330bbf5d7cd4fccc0f1b127c684c4a74 to your computer and use it in GitHub Desktop.
Save mariuszklinger/330bbf5d7cd4fccc0f1b127c684c4a74 to your computer and use it in GitHub Desktop.
custom infinite flat() in js
const example1 = [[1, 1, 1, [1.4, 1.6]], 666, [2, 3, [[4], [5, 6]]]];
function flat(arr) {
const stack = arr;
const result = [];
while (stack.length) {
const current = stack.shift();
const isCurrentArray = Array.isArray(current);
if (isCurrentArray) {
stack.unshift(...current);
continue;
}
result.push(current);
}
return result;
}
console.assert(`${flat(example1)}`, '1,1,1,1.4,1.6,666,2,3,4,5,6');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment