Last active
December 26, 2016 13:21
-
-
Save maximpn/1bbb14019593ab363edbaa30ed1a25c2 to your computer and use it in GitHub Desktop.
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
/** | |
* ES6 implementation of flatten function. | |
* It's sorter due to syntax sugar but usually consume more memory due to larger amount of function calls. | |
*/ | |
function flatten(arr) { | |
return arr.reduce( | |
(a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] | |
); | |
} |
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
/** | |
* Old style implementation of flatten function. It creates a new array and returns it. | |
*/ | |
function flatten(arr) { | |
var result = []; | |
for (let i = 0; i < arr.length; ++i) { | |
if (typeof arr[i] === "object") { // Check for an array | |
if (!arr[i].length) { | |
continue; // Skip objects | |
} | |
var flattenSubArray = flatten(arr[i]); | |
for (let j = 0; j < flattenSubArray.length; ++j) { | |
result.push(flattenSubArray[j]); | |
} | |
} else { | |
result.push(arr[i]); | |
} | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment