Skip to content

Instantly share code, notes, and snippets.

@Amitesh Amitesh/flatten.js
Created Dec 5, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.