Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Created January 27, 2019 23:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/ed39c15fcf863db89712be9a3bf384b4 to your computer and use it in GitHub Desktop.
Save Noitidart/ed39c15fcf863db89712be9a3bf384b4 to your computer and use it in GitHub Desktop.
function flattenRecur(arr) {
// arr is either array or non-array
if (!Array.isArray(arr)) return arr;
const newArr = [];
for (const el of arr) {
const flattened = flattenRecur(el);
if (Array.isArray(flattened)) newArr.push(...flattened);
else newArr.push(flattened);
}
return newArr;
}
function flattenIter(arr) {
const newArr = [];
const queue = arr.slice();
while (queue.length) {
const el = queue.shift();
if (Array.isArray(el)) queue.unshift(...el);
else newArr.push(el);
}
return newArr;
}
console.log(flattenIter([
1,
[2, 3],
4,
[5, [6, []], 7],
[[[[1]]]]
]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment