Skip to content

Instantly share code, notes, and snippets.

@r01010010
Last active January 15, 2017 17:38
Show Gist options
  • Save r01010010/c35404b7a5968049d891f563498124ab to your computer and use it in GitHub Desktop.
Save r01010010/c35404b7a5968049d891f563498124ab to your computer and use it in GitHub Desktop.
// 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