Skip to content

Instantly share code, notes, and snippets.

@genu
Created October 20, 2016 05:11
Show Gist options
  • Save genu/16e1c8d21169ecdb225e910ece6a5a1d to your computer and use it in GitHub Desktop.
Save genu/16e1c8d21169ecdb225e910ece6a5a1d to your computer and use it in GitHub Desktop.
Function to flatten an array
/**
* 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