Skip to content

Instantly share code, notes, and snippets.

@stephenway
Created February 7, 2019 15:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenway/65a55579889d630ca8f8d8f770bace51 to your computer and use it in GitHub Desktop.
Save stephenway/65a55579889d630ca8f8d8f770bace51 to your computer and use it in GitHub Desktop.
Flatten a nested array to a single level array
// Setup nested array
var array1 = [[1,2,[3]],4];
// Iterate over the nested array and reduce/concat
function flattenArray(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}
// Run the nested array through our function
flattenArray(array1);
// => [1, 2, 3, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment