0

//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.

Ivo Mori
  • 1,930
  • 5
  • 19
  • 29
Mozarts
  • 41
  • 4
  • Does this answer your question? [Merge/flatten an array of arrays](https://stackoverflow.com/questions/10865025/merge-flatten-an-array-of-arrays) – Ivo Mori May 20 '20 at 00:34
  • Welcome to SO. Remember, before asking a new question ___try searching SO for already existing answers___. If an already existing answer does not (fully) answer your question it's then great to start a new question referencing the existing question and elaborate further what's unanswered. Also have a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – Ivo Mori May 20 '20 at 00:43
  • As you already got an answer from @CertainPerformance remember to accept if it answers your question. – Ivo Mori May 20 '20 at 00:45
  • Actually, [this](https://stackoverflow.com/a/18307218/5698098) answer for the already mentioned question [Merge/flatten an array of arrays](https://stackoverflow.com/q/10865025/5698098) answers your question completely. – Ivo Mori May 20 '20 at 01:01

2 Answers2

3

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);
CertainPerformance
  • 260,466
  • 31
  • 181
  • 209
0

Another option - flatMap:

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

But it is only really advantageous if you want to do something inside the map, like this:

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

Or like this:

const arrays = [["how", "now"], ["brown", "cow"]];
const flattenedArray = arrays.flatMap(a => a.map(b => b.toUpperCase()));
console.log(flattenedArray);
Alex L
  • 3,643
  • 1
  • 7
  • 19