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

Total
0
Shares

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

Live Demo

Open Live Demo