Skip to content

Instantly share code, notes, and snippets.

@codenamezjames
Created January 1, 2019 16:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codenamezjames/cd60f59adb1717b7122a61624f33bc10 to your computer and use it in GitHub Desktop.
Save codenamezjames/cd60f59adb1717b7122a61624f33bc10 to your computer and use it in GitHub Desktop.
Javascript flatten similar to ruby's flatten
function flatten(arr, depth = Infinity, result = []) {
if(!Array.isArray(arr)) return null
for (const value of arr) {
if (depth > 0 && Array.isArray(value)) {
if (depth > 1) {
flatten(value, depth - 1, result)
} else {
result.push(...value)
}
} else {
result[result.length] = value
}
}
return result
}
// Tests
const superFlat = JSON.stringify(flatten( [[ [[[[1]]]], 2, [ 3 ] ], 4] )) === JSON.stringify([1, 2, 3, 4])
if ( !superFlat ) throw 'Failed to flatten many layers deep'
const oneLayer = JSON.stringify(flatten( [1,2,3,[[4]]], 1 )) === JSON.stringify([1,2,3,[4]])
if (!oneLayer) throw 'Failed to only flatten one layer'
const crazyInput = JSON.stringify(flatten( {1:1, 2:2, 3:3} )) === JSON.stringify(null)
if(!crazyInput) throw 'Does not handle crazy inputs'
console.log('Everything flattened successfully')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment