Created
July 20, 2017 14:05
-
-
Save shivendrasoni/3c5347e7e41fd8ee506a82d91dcba964 to your computer and use it in GitHub Desktop.
An array of arbitrarily nested arrays of integers into a flat array of integers
This file contains 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
/* | |
Deep Flatten a nested array. | |
Reduce if the child is an array, else concattenate the element to the the parent array. | |
*/ | |
var deepFlatten = (r, a) => Array.isArray(a) ? a.reduce(deepFlatten, r) : r.concat(a) | |
function test_flatten(){ | |
var arr1 = [[1,2,[3]],4]; | |
var arr2 = [1,[2,[3,[4],5,],6],7]; | |
var outputArray_1 = arr1.reduce(deepFlatten, []); | |
var outputArray_2 = arr2.reduce(deepFlatten, []); | |
console.log('Flattened array 1:', outputArray_1); | |
console.log('Flattened array 2:', outputArray_2); | |
} | |
test_flatten(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment