Skip to content

Instantly share code, notes, and snippets.

@dougg0k
Created February 22, 2019 12:32
Show Gist options
  • Save dougg0k/401ec9f2b1cc1f2712bd20357554827b to your computer and use it in GitHub Desktop.
Save dougg0k/401ec9f2b1cc1f2712bd20357554827b to your computer and use it in GitHub Desktop.
const arrayToFlat = [[1, 2, [3]], 4];
const arrayToFlat2 = [[1, 2, [3, [4]]], 5];
const arrayToFlat3 = [[1, 2, [3, [4, [5, 6, [7]]]]], 8];
const flatArray = arr => {
return arr.reduce(
(acc, curr) =>
Array.isArray(curr) ? acc.concat(flatArray(curr)) : acc.concat(curr),
[]
);
};
console.log(flatArray(arrayToFlat));
console.log(flatArray(arrayToFlat2));
console.log(flatArray(arrayToFlat3));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment