Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining disjointed arrays into one array [duplicate]

Tags:

javascript

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.

like image 514
umbriel Avatar asked Mar 01 '23 21:03

umbriel


2 Answers

You should use Array.flat

const strings = [["string1", "string2", "string3"], ["string4"],["string5", "string6"]]
console.log(strings.flat())
like image 185
Njuguna Mureithi Avatar answered Mar 11 '23 16:03

Njuguna Mureithi


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);
like image 29
ibrahim mahrir Avatar answered Mar 11 '23 15:03

ibrahim mahrir