Skip to content

Instantly share code, notes, and snippets.

@samdeesh
Created August 25, 2016 14:12
Show Gist options
  • Save samdeesh/33fde3387452698ae0f999b85f5f1331 to your computer and use it in GitHub Desktop.
Save samdeesh/33fde3387452698ae0f999b85f5f1331 to your computer and use it in GitHub Desktop.
Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
/**
*
*Code to flatten multidimensional array in javascript
*
*/
function flatten(array) {
return JSON.parse("[" +
JSON.stringify(array)
.replace(/[\[\]]+/g, "")
.replace(/,,/g, ",") +
"]");
}
var arr = [[1,2,[3]],4] ;
alert(flatten(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment