Skip to content

Instantly share code, notes, and snippets.

@powerslacker
Last active July 3, 2017 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save powerslacker/7ff6475d739de426794ce1cac3b935df to your computer and use it in GitHub Desktop.
Save powerslacker/7ff6475d739de426794ce1cac3b935df to your computer and use it in GitHub Desktop.
// 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]
function flatten (arr) {
let result = arr
// check if arr contains an array
while(result.find(item => Array.isArray(item))) {
// merge arr w/ top level arr
result = [].concat.apply([], result)
}
// when complete return flattened arr
return result
}
function testFlatten () {
let assertions = [
{
input: [ [1,2,[3, [4, 5]]], 6],
output: [1,2,3,4,5,6],
desc: 'test 3 level array'
},
{
input: [[1,2,[3]],4],
output: [1,2,3,4],
desc: 'test 2 level array'
},
]
assertions.forEach(assertion => {
if (!testArrayEquality(flatten(assertion.input), assertion.output)) {
console.warn(`Test failed - ${assertion.desc}`)
}
else {
console.log(`Test passed - ${assertion.desc}`)
}
})
}
function testArrayEquality (src, comparison) {
return src.length === comparison.length && src.every((item, index) => {
return item === comparison[index];
})
}
testFlatten()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment