Last active
January 15, 2017 17:38
-
-
Save r01010010/c35404b7a5968049d891f563498124ab to your computer and use it in GitHub Desktop.
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 1 (good performance) | |
function flat1(source) { | |
var s = "[" + JSON.stringify(source).replace(/\[|]/g,'') +"]"; | |
var flattened = JSON.parse(s); | |
} | |
console.log(flat1([[1,2,[3]],4, [[1,2,[3]],4], [[1,2,[3]],4], [[1,2,[3]],4]]); | |
// SOLUTION 2 (for small arrays) | |
function flat2(source, pos, prevs, final) { | |
let el = source[pos]; | |
if(Array.isArray(el)) { | |
prevs.unshift({ | |
source, | |
pos | |
}); | |
return flat(el, 0, prevs, final); | |
} else if (!isNaN(el)) { | |
final.push(el); | |
return flat(source, ++pos, prevs, final); | |
} else if(prevs.length >= 1){ | |
const prev = prevs.shift(); | |
return flat(prev.source, ++prev.pos, prevs, final); | |
} else { | |
return final; | |
} | |
}; | |
const arr = [[1,2,[3, [5, 7, 6, [3, 2, 4, [4, [3, [2, [1]]]]]]]],4, 2, 1, 5, 6, 3, 3, 1, 5]; | |
const final = flat2(arr, 0, [], []); | |
console.log(final); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment