Last active
May 2, 2017 13:21
-
-
Save hbarudin/d4106f4d2551687f56afb941aa706234 to your computer and use it in GitHub Desktop.
Flatten an arbitrarily nested array (JS)
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
/* | |
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]. | |
*/ | |
var array_flatten = function (arr, flattened_arr = []) { | |
if(!Array.isArray(arr)) { | |
// Fow now, arbitrarily decide to just break out if input is invalid. Could handle other ways (return an empty array, for example), but this is OK for now. | |
console.error('Invalid input.'); | |
return; | |
} | |
for (let el of arr) { | |
if (Array.isArray(el)) { | |
array_flatten(el, flattened_arr); | |
} else { | |
flattened_arr.push(el); | |
} | |
} | |
return flattened_arr; | |
} | |
// Some basic reality-check testing. Not necessarily the best, but definitely better than nothing. | |
console.assert(JSON.stringify(array_flatten([[1,2,[3]],4])) == '[1,2,3,4]', "Flatten deeply nested array"); | |
console.assert(JSON.stringify(array_flatten([1,2,3,4])) == '[1,2,3,4]', "Does not mess with already flat array"); | |
console.assert(JSON.stringify(array_flatten(null)) === undefined, "Does not explode with null input"); | |
console.assert(JSON.stringify(array_flatten([1,2,null,[3,null]])) === "[1,2,null,3,null]", "Does not explode with null elements"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment