Skip to content

Instantly share code, notes, and snippets.

@subhog
Last active August 30, 2016 10:24
Show Gist options
  • Save subhog/9f170fea1c4638f043e6b88fb0a459ab to your computer and use it in GitHub Desktop.
Save subhog/9f170fea1c4638f043e6b88fb0a459ab to your computer and use it in GitHub Desktop.
Flatten array exercise (JS)
// See live demo: https://repl.it/DCWZ
// Flatten array exercise
// Hubert Orlik–Grzesik
// hubert@orlikarnia.com
// 2016C
// Of course, in real-life environment I would write:
//
// import _ from 'lodash';
// _.flattenDeep(array);
//
// We use a separate subroutine so that the main method
// takes only the expected arguments.
// Subroutine:
// Iterate through all the leaf elements
// and push them to the target array.
const flattenTo = (target, source) => {
source.forEach(el => {
if(Array.isArray(el)) // Found an array, iterate through children
flattenTo(target, el);
else // Not an array, push to target flat array
target.push(el);
});
return target; // Return the target so that the main procedure
// can be a one-liner :-)
};
// Main method:
// Push all the leaf elements to a new empty array.
const flatten = array => flattenTo([], array);
// Some examples
console.log(flatten([2,3,4,5,6,7,8,9]));
console.log(flatten([[2,3], [4,5], [6,7], [8,9]]));
console.log(flatten([[[[2,3]]], [4,[5]], [6,7, [[8],9]]]));
console.log(flatten([[[[2,[[[3]]]]]], [4,[5]], [[6,7], [[8],9]]]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment