Skip to content

Instantly share code, notes, and snippets.

@jigar1101
Last active May 31, 2019 08:23
Show Gist options
  • Save jigar1101/e4f7b0d4d7f97a0e52f4093725342a1c to your computer and use it in GitHub Desktop.
Save jigar1101/e4f7b0d4d7f97a0e52f4093725342a1c to your computer and use it in GitHub Desktop.
/*
* The below code flattens an arbitrarily nested arrays
* eg:- [1,2,[3]],4] -> [1,2,3,4]
*/
//User Input - Array that is to be flattened
var arrInput = [[1,2,[3]],4]
/*
* Method to flatten an array
* It converts the complete array into a string which will be comma separated
* using the toString native javascript method & then splits using operator ','
*/
var getFlattenedArray = function getFlattenedArray(arrInput) {
return arrInput.toString().split(',')
}
//Output - Flattened array
var flattenedArray = getFlattenedArray(arrInput)
console.log(flattenedArray) //Prints the flattened array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment