Skip to content

Instantly share code, notes, and snippets.

@codeepic
Last active November 16, 2018 16:36
Show Gist options
  • Save codeepic/ef9de9290da9574f1ea1 to your computer and use it in GitHub Desktop.
Save codeepic/ef9de9290da9574f1ea1 to your computer and use it in GitHub Desktop.
Array Flattener in JS
var a = [[1,2,[3]],4, [5, [6, 7, [8, [9]]]]];
function flattenNestedArrays(arr){
var flattenedArray = [];
(function flattenArray(arr){
arr.forEach(function(item){
if(Array.isArray(item)){
flattenArray(item);
}else{
flattenedArray.push(item);
}
});
})(arr);
return flattenedArray;
}
console.log(flattenNestedArrays(a)); // [1,2,3,4,5,6,7,8,9]
@codeepic
Copy link
Author

codeepic commented Nov 16, 2018

Or simpler:

function flatMapDeep(arr, flat = []){
    return arr.reduce((accum, el) => {
        if(Array.isArray(el)){
          return flatMapDeep(el, flat);
        } else {
          accum.push(el);
          return accum;
        }
    }, flat);
}

var b = [[2,3, [33]], 9, 8, [2,3]];

var flattened = flatMapDeep(b);

console.log('flattened:    ', flattened);

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