Created
March 27, 2018 09:14
-
-
Save enricolucia/43a89e73bd15707d6799cc05730053f7 to your computer and use it in GitHub Desktop.
Deep array flatten function
This file contains 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
// SOLUTION: | |
// Turns out that the following is the most performant in terms of ops per seconds. | |
// It iterates on an array, staying within the "while loop" as long as | |
// the current item exists. Checking also whether using concat to the very same "arr" argument | |
// or push methods in a new stack array until no items are left within the "arr" argument | |
const flattenLoop = arr => { | |
let stack = [] | |
let item | |
while (item = arr.shift()) { | |
if (Array.isArray(item)) { | |
arr = item.concat(arr) | |
} else { | |
stack.push(item) | |
} | |
} | |
return stack | |
} | |
// ALTERNATIVE APPROACH (less performant, but suggested as per MDN): | |
// This function is inspired by the following MDN "Alternative" section | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatten | |
// and the draft proposal https://tc39.github.io/proposal-flatMap/#sec-Array.prototype.flatten | |
const flatten = (list) => { | |
// Reducing everything to a single array | |
return list.reduce((acc, val) => { | |
// Checking whether return as param to concat straight val or go "flatten" | |
// one level deeper for a nested array | |
return acc.concat(Array.isArray(val) ? flatten(val) : val) | |
}, []) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment