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.
You should use Array.flat
const strings = [["string1", "string2", "string3"], ["string4"],["string5", "string6"]]
console.log(strings.flat())
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With