Use _.concat(array, [values])
function of Lodash to concat multiple arrays, nested arrays and individual values.
Suppose you have the below values to concat β
// Marvel Superheroes array π marvel = ["Ironman", "Hulk"] // DC superheroes array π dc = ["Superman", "Batman"] // Science superhero π real = "Nicola Tesla" // Real Life superheroes in nested array π nested = [["Mother", "Father"], ["Teachers", "Doctors"]]
Now after concatenation, they should look like this β
superheroes = ["Ironman", "Hulk", "Superman", "Batman", "Nicola Tesla", ["Mother", "Father"], ["Teachers", "Doctors"]]
We can achieve this result using _.concat(array, [values])
where β
-
array
β An initial array in which other values needs to be concatenated. -
values
β Any number of arrays, individual values etc.
Note
_.concat
doesnβt change the array. It will create a new concatenated array and return that.
Code Example
1. Using Javascript & Lodash
// Marvel Superheroes array π marvel = ["Ironman", "Hulk"] // DC superheroes array π dc = ["Superman", "Batman"] // Science superhero π real = "Nicola Tesla" // Real Life superheroes in nested array π nested = [["Mother", "Father"], ["Teachers", "Doctors"]] console.log(_.concat(marvel, dc, real, nested)) // Output π ["Ironman", "Hulk", "Superman", "Batman", "Nicola Tesla", ["Mother", "Father"], ["Teachers", "Doctors"]]
2. Using ReactJS & Lodash
import _ from "lodash"; export default function App() { const marvel = ["Ironman", "Hulk"] const dc = ["Superman", "Batman"] const real = "Nicola Tesla" const nested = [["Mother", "Father"], ["Teachers", "Doctors"]] return <pre>{JSON.stringify(_.concat(marvel, dc, real, nested), null, "\t")}</pre>; } // Output π /* [ "Ironman", "Hulk", "Superman", "Batman", "Nicola Tesla", [ "Mother", "Father" ], [ "Teachers", "Doctors" ] ] */
It can also support concatenation of objects array. Check the below code β
const arr1 = [1, 3] const arr2 = [{a: 1, b: 2}] console.log(_.concat(arr1, arr2)) // Output π [1, 3, {a: 1, b: 2}]