Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening nested array in JavaScript

I have a horrible looking array which looks like this:

EDIT:

array = [
    {
        Letters: [{ Letter: 'A' }, { Letter: 'B' }, { Letter: 'C' }],
        Numbers: [{ Number: '1' }, { Number: '2' }, { Number: '3' }]
    },
    null,
    {
        Letters: [{ Letter: 'D' }, { Letter: 'E' }, { Letter: 'F' }, { Letter: 'G' }, { Letter: 'H' }],
        Numbers: [{ Number: '4' }, { Number: '5' }, { Number: '6' }, { Number: '7' }]
    }
];

And want the array to look like this:

flattenedArray = [a,b,c,1,2,3,d,e,f,g,h,4,5,6,7]

Unfortunately I cannot change the original formatting because that is the form received when merging two API responses that I am getting.

I have tried using:

var flattenedArray = [].concat.apply([], array);

But it just presents the array in the same format it was entered in.

I was wondering if anybody had any advice?

EDIT: I have tried implementing the suggestions given - thank you so much for your help. It seems it is a problem with the format of the list - unfortunately using the chrome console which is in a 'tree' format I cannot see the direct structure of the array output.

Thank you for all your help! EDIT 2: See above for the actual array, thank you for showing me how to see this!

like image 864
Jess Avatar asked Dec 26 '16 11:12

Jess


2 Answers

Implement flatten function using recursion and spread operator.

const a = [1,[2,[3,4],[5]],6];
const flatten = (arr) => {
    const res = []
    for(let i=0;i<arr.length;i++) {
        if(!Array.isArray(arr[i])) res.push(arr[i]);
        else res.push(...flatten(arr[i]));
    }
    return res;
}
console.log(flatten(a));
like image 102
Maneesh Reddy Avatar answered Oct 05 '22 23:10

Maneesh Reddy


No one thought of splicing in-place?

function flatten(array){
    for (var i = 0; i < array.length; i++) {
        if(array[i] instanceof Array){
            array.splice.apply(array,[i,1].concat(array[i]));
            i--;
        }
    };
    return array;
}

One iteration, no recursion.

like image 42
Rick Edwards Avatar answered Oct 06 '22 00:10

Rick Edwards