Skip to content

Instantly share code, notes, and snippets.

@MurhafSousli
Last active August 23, 2016 06:20
Show Gist options
  • Save MurhafSousli/296859e76ffb531aa4c3318d13260b7c to your computer and use it in GitHub Desktop.
Save MurhafSousli/296859e76ffb531aa4c3318d13260b7c to your computer and use it in GitHub Desktop.
Javascript array flattening
/**
* Flattens an array of arbitrarily nested arrays into
* a flat array. e.g. [[1,2,[3]],4] -> [1,2,3,4]
*
* @param items - source array
* @return - flat array
*/
function flatten(items) {
const flat = [];
items.forEach(item => {
if (Array.isArray(item)) {
flat.push(...flatten(item));
} else {
flat.push(item);
}
});
return flat;
}
/** @TEST */
var arr = [[1,2,[3]],4];
console.log('before: ' + JSON.stringify(arr));
console.log('after: ' + JSON.stringify(flatten(arr)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment