Created
January 21, 2018 11:56
-
-
Save luzeduardo/dcb8fe64369106ac2bdaf3506409d4ce to your computer and use it in GitHub Desktop.
JS flatt depth arrays
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
| 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