Created
June 26, 2017 18:00
-
-
Save mbenedettini/cab0566847be13c634d428bddf63315d to your computer and use it in GitHub Desktop.
Flatten nested array of integers
This file contains hidden or 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
/* I've chosen Javascript as it has become my main language nowadays. I tried | |
to avoid high level functions () and stick to just the basic stuff. | |
*/ | |
function flatten(object) { | |
return object.reduce((a, b) => { | |
if (Array.isArray(b)) { | |
return a.concat(flatten(b)); | |
} else { | |
return a.concat(b); | |
} | |
}, []); | |
} | |
/* Usually my Javascript scripts have this section at the end, which is | |
the equivalent of | |
if __name__ == '__main__' | |
in Python */ | |
if (require.main === module) { | |
let exampleList = [[1,2,[3]],4]; | |
let flattenedList = flatten(exampleList); | |
console.log('example list: ', exampleList); | |
console.log('flattened list:', flattenedList); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment