Skip to content

Instantly share code, notes, and snippets.

@trainbolt
Created May 16, 2019 18:43
Show Gist options
  • Save trainbolt/592494f83e7a5b0299dbdb833128f3bb to your computer and use it in GitHub Desktop.
Save trainbolt/592494f83e7a5b0299dbdb833128f3bb to your computer and use it in GitHub Desktop.
Flatten nested arrays
const n = [1,[2,[3,4,5]],6,[7,[8],[9,[10]]]];
const n2 = [1,[2,[3,[4,[5],6],7],8],9];
/**
* Flattens arbitrarilily nested arrays. Pulls off the first item (a) from the array
* and preserves the rest (arr) using the spread operator.
*
* @param {Array} [] The nested array to flatten
* @param {Array} flat The nested array to flatten
* @returns {Array} Recursively returns a flattened array
*/
const flatten = (arr, flat=[]) => {
arr.forEach(a => Array.isArray(a) ? flatten(a, flat) : flat.push(a));
return flat;
}
/**
* Flattens arbitrarilily nested arrays. Pulls off the first item (a) from the array
* and preserves the rest (arr) using the spread operator.
*
* @param {Array} [] The nested array to flatten
* @returns {Array} Recursively returns nested arrays deepest -> shallow
*/
const flatten2 = ([a, ...arr]) => a ? [...(Array.isArray(a) ? flatten2(a) : [a]), ...flatten2(arr)] : [];
/*
* The spread operator in flatten2 is basically the same exact idea of arr.forEach(a... in flatten.
* It picks off the first item and then returns the rest using the reversed spread operator. Similar in
* a way to Array.shift().
*/
console.log(flatten(n));
console.log(flatten(n));
// Result should be:
// Array(10) [1,2,3,4,5,6,7,8,9,10]
// Array(10) [1,2,3,4,5,6,7,8,9,10]
console.log(flatten(n2));
console.log(flatten(n2));
// Result should be:
// Array(9) [1,2,3,4,5,6,7,8,9]
// Array(9) [1,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