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}]