Last active
June 14, 2020 07:58
-
-
Save hackash/800893b22138b472b139b5ba0e5a9092 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
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
function isArray(arr) { | |
return Object.prototype.toString.call(arr) === '[object Array]'; | |
} | |
function arrToFlat(arr, arrToReturn) { | |
if (!isArray(arr)) { | |
return false; | |
} | |
if (!arrToReturn) { | |
arrToReturn = []; | |
} | |
var i = 0, max = arr.length; | |
for (; i < max; i++) { | |
if (isArray(arr[i])) { | |
arrToFlat(arr[i], arrToReturn); | |
} else { | |
arrToReturn.push(arr[i]); | |
} | |
} | |
return arrToReturn; | |
} | |
console.log(arrToFlat([[1, 2, [3]], 4, [5, 6, 7, [8]]])); // output [1, 2, 3, 4, 5, 6, 7, 8] | |
console.log(arrToFlat([1, 2, 3, [4]])); // output [1, 2, 3, 4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment