Skip to content

Instantly share code, notes, and snippets.

@MeyCry
Last active January 20, 2020 22:53
Show Gist options
  • Save MeyCry/ee1e47f4d0f0db3571a05d0e279a245d to your computer and use it in GitHub Desktop.
Save MeyCry/ee1e47f4d0f0db3571a05d0e279a245d to your computer and use it in GitHub Desktop.
flatter for array
function flatter(arr) {
return arr.flat(Infinity);
}
flatter(
[1, 2, [3, 4, [5]], 6, [[7, [8]], 9]],
);
function flatter2(arr) {
const arrCopy = arr.slice();
const result = [];
while (arrCopy.length) {
const next = arrCopy.pop();
if (Array.isArray(next)) {
arrCopy.push(...next);
} else {
result.push(next);
}
}
return result.reverse();
}
flatter2([1, 2, [3, 4, [5]], 6, [[7, [8]], 9]]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment