4

I have a map that returns a disjointed list of arrays.

(3) ["string1", "string2", "string3"]
(1) ["string4"]
(2) ["string5", "string6"]

How can I get

(6) ["string1", "string2", "string3", "string4", "string5", "string6"]

I've tried concat(), Set(), Map(). but cant wrap my head around it.

umbriel
  • 723
  • 1
  • 7
  • 22

2 Answers2

4

You should use Array.flat

const strings = [["string1", "string2", "string3"], ["string4"],["string5", "string6"]]
console.log(strings.flat())
Njuguna Mureithi
  • 3,506
  • 1
  • 21
  • 41
3

Use Array#flat like so:

let flattenedArray = arrayOfArrays.flat();

let arr = [
  ["string1", "string2", "string3"],
  ["string4"],
  ["string5", "string6"]
];

let result = arr.flat();

console.log(result);

Note: if the array of arrays is the result of a map, you can do both (mapping and flattening) in one step by using Array.flatMap instead like so:

let flattenedArray = originalArray.flatMap( /* callback that returns subarrays */ );

let arr = [
  "string1-string2-string3",
  "string4",
  "string5-string6"
];

let result = arr.flatMap(str => str.split("-"));

console.log(result);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
  • Hi thanks for looking into this, however in your second example my arrays are not joined by dashes so its solving another problem unfortunately. – umbriel Nov 29 '20 at 12:40
  • @umbriel that was just a demo to show you how `flatMap` works, the callback can be anything that returns arrays, I just used `split` for demonstration. Just replace `map` with `flatMap` in your code and it will work – ibrahim mahrir Nov 29 '20 at 12:48