Created
September 19, 2016 14:48
-
-
Save chenghaoc/9dcfa81aaad1451114cd26da320a9b10 to your computer and use it in GitHub Desktop.
Array flatten
This file contains hidden or 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
// 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