Created
February 7, 2019 15:58
-
-
Save stephenway/65a55579889d630ca8f8d8f770bace51 to your computer and use it in GitHub Desktop.
Flatten a nested array to a single level array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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