Skip to content

Instantly share code, notes, and snippets.

@bananasmoothii
Forked from Integralist/flatten-array.js
Last active February 22, 2021 23:08
Show Gist options
  • Save bananasmoothii/55e46c237dcfabdd209e162299aabd61 to your computer and use it in GitHub Desktop.
Save bananasmoothii/55e46c237dcfabdd209e162299aabd61 to your computer and use it in GitHub Desktop.
Array flatten function written in ES6 syntax
function flat(array, depth = 1) {
let result = [];
if (depth !== 1) {
result = array;
for (let i = 0; i < depth; i++) {
result = flat(result);
}
return result;
}
for (let element of array) {
if (Array.isArray(element)) {
if (element.length > 0) { // we don't want to go in the else if the array is empty
for (let subElement of element) {
result.push(subElement);
}
}
}
else {
result.push(element);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment