Skip to content

Instantly share code, notes, and snippets.

@Boo-urns
Created December 2, 2016 05:10
Show Gist options
  • Save Boo-urns/2df8c502c905bf61ac42b8d7870aa2d3 to your computer and use it in GitHub Desktop.
Save Boo-urns/2df8c502c905bf61ac42b8d7870aa2d3 to your computer and use it in GitHub Desktop.
Flatten an array of nested arrays
/*
* flatten_arr(array)
* Purpose: Flatten an array of nested arrays
*
* Usage:
* var arrayToFlatten = flatten_arr([[1,2,[3]],4]); // [1,2,3,4]
*
* // If not passing an array it returns the initial value
* var notArray = flatten_arr('5'); // '5' returns initial value
*/
function flatten_arr(arr) {
// If argument is not an array return
if(!Array.isArray(arr)) {
console.error("flatten_arr - Argument is not an array");
// Return initial value.
return arr;
}
var reduced = arr.reduce(function(outputArr, currentVal) {
return outputArr.concat(currentVal);
}, []);
// Check if any arrays are nested past the inital reduce
for(prop of reduced) {
if(Array.isArray(reduced[prop])) {
return flatten_arr(reduced);
}
}
return reduced;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment