Created
March 5, 2020 15:03
-
-
Save prashantsani/21b6a16b58ce7ae3e361b35a0eec375f to your computer and use it in GitHub Desktop.
Flatten An array of Integers not using Array.flat()
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
| // Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. | |
| // e.g. [[1,2,[3]],4] -> [1,2,3,4]. | |
| function flatten(arr){ | |
| let newArray = []; | |
| for(let i=0; i< arr.length; i++){ | |
| if(Array.isArray(arr[i])){ | |
| newArray = newArray.concat(flatten(arr[i])) | |
| }else{ | |
| newArray.push(arr[i]) | |
| } | |
| } | |
| return newArray; | |
| } | |
| console.log(flatten([[1,2,[3]],4])); | |
| console.log(flatten([[1,33,22,[[[12]]],[3]],4])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment