How to concat arrays and values in javascript, reactjs and lodash?

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 –

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

Live Demo

Open Live Demo