Created
August 1, 2022 07:59
-
-
Save owade/d6af7819f6dbffd5c16b0838709b446a to your computer and use it in GitHub Desktop.
Ways to flatten nested array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The method using splice is faster...