Created
October 20, 2016 05:11
-
-
Save genu/16e1c8d21169ecdb225e910ece6a5a1d to your computer and use it in GitHub Desktop.
Function to flatten an array
This file contains 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
/** | |
* Recursivelly flattens an array | |
* | |
* @param {Array} input The input array | |
* @return {Array|Number} Flattened array or -1 if the input is invalid | |
*/ | |
function flatten (input) { | |
if(!Array.isArray(input)) { | |
return -1; | |
} | |
return input.reduce(function (flat, flattenable) { | |
if (Array.isArray(flattenable)) { | |
return flat.concat(flatten(flattenable)); | |
} else { | |
return flat.concat(flattenable); | |
} | |
}, []); | |
} | |
// Tests | |
var array1 = [[1, 2, [3]], 4]; | |
var array2 = [5, [1, [2], [3]], 4, {n:1}]; | |
var invalid1 = 'invalid input'; | |
console.log(flatten(array1)); | |
console.log(flatten(array2)); | |
console.log(flatten(invalid1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment