Skip to content

Instantly share code, notes, and snippets.

@maximpn
Last active December 26, 2016 13:21
Show Gist options
  • Save maximpn/1bbb14019593ab363edbaa30ed1a25c2 to your computer and use it in GitHub Desktop.
Save maximpn/1bbb14019593ab363edbaa30ed1a25c2 to your computer and use it in GitHub Desktop.
/**
* 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), []
);
}
/**
* 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