Created
December 5, 2016 17:38
-
-
Save Amitesh/6ea7feec3d0c76bf37ea76a1168cf2a9 to your computer and use it in GitHub Desktop.
Flatten the deep nested 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
/** | |
* Function to flatten the deep array | |
*/ | |
var sampleArray = [[1, 2],[3, 4, 5], [6, 7, 8, 9]]; | |
// Solution for single level nested array | |
[].concat.apply([], sampleArray); | |
// If we want deep flatten then we can use recursive function strategy | |
function flatten(inputArray) { | |
return inputArray.reduce(function (a, b) { | |
return a.concat(Array.isArray(toFlatten) ? flatten(b) : b); | |
}, []); | |
} | |
// Tests | |
var sampleArray2 = [[1, 2],[3, 4, 5], [6, 7, [8, [9]]]]; | |
console.log(flatten(sampleArray2)); | |
// [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