Skip to content

Instantly share code, notes, and snippets.

@luzeduardo
Created January 21, 2018 11:56
Show Gist options
  • Select an option

  • Save luzeduardo/dcb8fe64369106ac2bdaf3506409d4ce to your computer and use it in GitHub Desktop.

Select an option

Save luzeduardo/dcb8fe64369106ac2bdaf3506409d4ce to your computer and use it in GitHub Desktop.
JS flatt depth arrays
export const flattner = array => {
if (!Array.isArray(array)) {
throw Error(`${array} is not an Array`)
}
for (let i = 0; i < array.length;) {
let value = array[i]
if (Array.isArray(value)) {
if (value.length > 0) {
value.unshift(i, 1)
array.splice.apply(array, value)
value.splice(0, 2)
} else {
array.splice(i, 1)
}
} else {
i++
}
}
return array;
}
if (!flattner([1]) === [1]){
throw Error(`Failure`)
}
if (!flattner([[1]]) === [1]){
throw Error(`Failure`)
}
if (!flattner([1,[1]]) === [1,1]){
throw Error(`Failure`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment