Skip to content

Instantly share code, notes, and snippets.

@oscarcp777
Last active November 19, 2017 00:48
Show Gist options
  • Save oscarcp777/c87f761623b986f87c2ee8e3930b1320 to your computer and use it in GitHub Desktop.
Save oscarcp777/c87f761623b986f87c2ee8e3930b1320 to your computer and use it in GitHub Desktop.
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].
// version 1
const flat = (array) => {
let list=[]
array.map((item) => {
if(Array.isArray(item)){
list=[...list,...flat(item)]
}else{
list.push(item)
}
})
return list
}
// version 2
const flatten = (array) =>{
return array.reduce((prev,current)=>{
return Array.isArray(current) ? prev.concat(flatten(current)) : prev.concat(current)
},[])
}
let original1 = [[1,2,[3]],[[[[4]],[6]],[[7]]],8]
let original2 =[[1,2,[3]],4]
console.assert( JSON.stringify([ 1, 2, 3, 4, 6, 7, 8 ]) === JSON.stringify(flatten(original1)),
{"message":"sorry: flatten fail the test"} )
console.assert( JSON.stringify([ 1, 2, 3, 4]) === JSON.stringify(flatten(original2)),
{"message":"sorry: flatten fail the test"} )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment