Skip to content

Instantly share code, notes, and snippets.

@owade
Created August 1, 2022 07:59
Show Gist options
  • Save owade/d6af7819f6dbffd5c16b0838709b446a to your computer and use it in GitHub Desktop.
Save owade/d6af7819f6dbffd5c16b0838709b446a to your computer and use it in GitHub Desktop.
Ways to flatten nested array
//stackoverflow
function flatten(arr) {
let i = 0;
if (!Array.isArray(arr)) {
/* return non-array inputs immediately to avoid errors */
return arr;
}
while (i < arr.length) {
if (Array.isArray(arr[i])) {
arr.splice(i, 1, ...arr[i]);
} else {
i++;
}
}
return arr;
}
var flatten = arr => {
let res = [];
for(let i = 0;i<arr.length;i++){
if(Array.isArray(arr[i])) {
res.push(...arr[i]);
} else {
res.push(arr[i]);
}
if(i === arr.length-1 && hasArray(res)){
//reset old arr to new
arr = res;
//clear res
res = [];
//restart loop wohoo!
i=-1;
continue;
}
}
return res;
}
const hasArray = (arr) => {
for(let i=0;i<arr.length;i++){
if(Array.isArray(arr[i])){
return true;
}
}
return false
}
@owade
Copy link
Author

owade commented Aug 1, 2022

console.log(flatten([1,2,[3,4,[5,6,7,[8,9,[10,[11,12,[13,14,[15,16]]]]]]]]));
[
   1,  2,  3,  4,  5,  6,
   7,  8,  9, 10, 11, 12,
  13, 14, 15, 16
]

The method using splice is faster...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment