Skip to content

Instantly share code, notes, and snippets.

@chenghaoc
Created September 19, 2016 14:48
Show Gist options
  • Save chenghaoc/9dcfa81aaad1451114cd26da320a9b10 to your computer and use it in GitHub Desktop.
Save chenghaoc/9dcfa81aaad1451114cd26da320a9b10 to your computer and use it in GitHub Desktop.
Array flatten
// For browser not complete support ES6, should transpile to ES5 using Babel
function flatten(input, output = []) {
if (Array.isArray(input)) {
input.forEach(ele => {
if (Array.isArray(ele)) {
flatten(ele, output)
} else {
output.push(ele)
}
})
}
return output
}
// Test helper
function equalArray(arr1, arr2) {
if (arr1.length === arr2.length) {
for (let i = 0; i < arr1.length; i ++) {
if (arr1[i] !== arr2[i]) {
return false
}
}
return true
}
return false
}
// Test
console.log(equalArray(flatten([[1, 2, [3]], 4]), [1, 2, 3, 4]))
console.log(equalArray(flatten([1, 2, [[]]]), [1, 2]))
const a = { foo: 3 }, b = { bar: 4 }
console.log(equalArray(flatten([1, [a], b]), [1, a, b]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment