Skip to content

Instantly share code, notes, and snippets.

@Amitesh
Created December 5, 2016 17:38
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 Amitesh/6ea7feec3d0c76bf37ea76a1168cf2a9 to your computer and use it in GitHub Desktop.
Save Amitesh/6ea7feec3d0c76bf37ea76a1168cf2a9 to your computer and use it in GitHub Desktop.
Flatten the deep nested array
/**
* 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