Search code examples
javascriptarraysconcatenationreduce

How can I reduce or flatten an array of arrays using the Array.concat() method inside the callback function for Array.reduce()



//Bonus - uncomment lines 15 and 17
const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.reduce((a,c) => a + c);
// The below line should console.log: ["how", "now", "brown", "cow"]
console.log(flattenedArray);

I'm new to using the reduce function and it's a little bit complicated.

I'm trying to flatten the nested array but I don't really know what to do next.


Solution

  • You mentioned the solution already, you just need to implement it - concat the current item to the accumulator inside the reduce callback:

    const arrays = [["how", "now"], ["brown", "cow"]];
    const flattenedArray = arrays.reduce((a,c) => a.concat(c));
    console.log(flattenedArray);

    But .flat() would be much easier:

    const arrays = [["how", "now"], ["brown", "cow"]];
    const flattenedArray = arrays.flat();
    console.log(flattenedArray);