Skip to content

Instantly share code, notes, and snippets.

@mbenedettini
Created June 26, 2017 18:00
Show Gist options
  • Save mbenedettini/cab0566847be13c634d428bddf63315d to your computer and use it in GitHub Desktop.
Save mbenedettini/cab0566847be13c634d428bddf63315d to your computer and use it in GitHub Desktop.
Flatten nested array of integers
/* 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