Skip to content

Instantly share code, notes, and snippets.

@tomatau
Last active March 26, 2017 12:49
Show Gist options
  • Save tomatau/9feead885f863699ec2f11e0d52ae9d5 to your computer and use it in GitHub Desktop.
Save tomatau/9feead885f863699ec2f11e0d52ae9d5 to your computer and use it in GitHub Desktop.
Array Flatten
const flatten = (source) => {
const length = source.length
let i = 0
let flattened = []
for (; i < length; i++) {
// recursive call could reach stack limit
flattened = flattened.concat(
!Array.isArray(source[i]) ? source[i] : flatten(source[i])
)
// could iterate and expand first item in array until not an array
// then push onto flattened output
}
return flattened
}
console.assert(
arrayEqual(
flatten([ 1, 2, 3, 4 ]),
[ 1, 2, 3, 4 ]
),
`doesn't work with flat arrays`
)
console.assert(
arrayEqual(
flatten([ [ 1, 2, [ 3 ] ], 4 ]),
[ 1, 2, 3, 4 ]
),
`doesnt flatten simple nested arrays`
)
const deeplyNestedArray = Array.from({ length: 10000 }).reduce(acc => [ acc ], 0)
console.assert(
arrayEqual(
flatten(deeplyNestedArray),
[ 0 ]
),
`doesn't flatten deeply nested array`
)
function arrayEqual(arr1, arr2) {
const length = arr1.length
let i = 0
if (length !== arr2.length) return false
for (; i < length; i++)
if (arr1[i] !== arr2[i])
return false
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment