Skip to content

Instantly share code, notes, and snippets.

@jasonwaters
Created October 12, 2016 20:08
Show Gist options
  • Save jasonwaters/ffa6a642c7a6a6c940a770c620707433 to your computer and use it in GitHub Desktop.
Save jasonwaters/ffa6a642c7a6a6c940a770c620707433 to your computer and use it in GitHub Desktop.
var a = [1, {a: [2, [3]]}, 'four', [[5], [6]], [[7], 8, 9], 10];
function flatten(arr) {
let idx = 0;
while(idx < arr.length) {
if(arr[idx] instanceof Array) {
Array.prototype.splice.apply(arr, [idx, 1].concat(arr[idx]));
}else {
idx++;
}
}
}
flatten(a);
console.log(a);
@jasonwaters
Copy link
Author

function flattenArray(arr, flattened=[]) {
    for(let item of arr) {
        if(item instanceof Array) {
            flattenArray(item, flattened);
        }else {
            flattened.push(item);
        }
    }
    return flattened;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment