Last active
October 23, 2018 20:05
-
-
Save rob2d/049388188bbf720ca3904d809809b3fe to your computer and use it in GitHub Desktop.
Simple function to flatten an array. To easily verify results, download zip and run `test-cases.js` in Node
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
/** | |
* Flatten any combination of nested ints/arrays | |
* in an array recursively into a flat array | |
* @param input {Array} | |
* @returns {Array} | |
*/ | |
function flatten(input) { | |
let output = []; | |
for(let i = 0; i < input.length; i++) { | |
const item = input[i]; | |
// recursively add arrays | |
if(typeof item == 'object' && Array.isArray(item) && item.length) { | |
output.push(...flatten(item)); | |
} | |
// add simple number instances | |
if(typeof item == 'number') { | |
output.push(item); | |
} | |
} | |
return output; | |
} | |
module.exports = flatten; |
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
const flatten = require('./flatten'); | |
console.log('flatten([]) ->', flatten([])); | |
console.log('flatten([1,2,3]) ->', flatten([1,2,3])); | |
console.log('flatten([[1,2,[3]],4]) ->', flatten([[1,2,[3]],4])); | |
console.log('flatten([1,[],[2]) ->', flatten([1,[],[2]])); | |
console.log('flatten([1,[[]],[3]) ->', flatten([1,[[]],[3]])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment