Skip to content

Instantly share code, notes, and snippets.

@th91vi
Created August 8, 2023 12:19
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 th91vi/25d274a4257e581ae9dee38af7ef5ff7 to your computer and use it in GitHub Desktop.
Save th91vi/25d274a4257e581ae9dee38af7ef5ff7 to your computer and use it in GitHub Desktop.
Flatten array
const array = [1, [2, [3]], 4, []];
const flatter = (array) => {
let flatArray = [];
array.forEach((item, index) => {
if (Array.isArray(item)) {
flatArray = flatArray.concat(flatter(array[index]));
} else {
flatArray.push(item);
}
});
return flatArray;
};
console.log(flatter(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment