How To Merge Two Arrays In React.js

How to merge two Arrays in React.js

This article will show you how to merge two arrays in React.js in a few straightforward ways, like using the concat() or spread operator method. Let’s go into detail now.

How to merge two arrays in React.js 

Using concat() method

In JavaScript, the function concat() refers to join two or more arrays. Additionally, it can alter the original array’s value and create a new array. How each of us programmers merges the JavaScript array determines whether or not we can alter the original array.

Syntax:

array1.concat(array2, array3, ..., arrayX)

Parameters:

  • array1,array2, array3, …, arrayX are the arrays you want to join together.

You can use Array. concat() to concatenate array1 with array2, and it will return a new array that is the combination of the two arrays passed in.

Code:

import { useState } from "react";
 
 export default function App() {
  var array1 = ["one", "two"];
  var array2 = ["three", "four", "five"];
  const [mergeArray,setMergeArray]=useState(array1.concat(array2))
  return (
    <div>
      <h2>How to merge two Arrays in React.js | LearnShareIT</h2>
      <p>{JSON.stringify(mergeArray)}</p>
    </div>
  );
}

Output:

So you can merge two arrays in React.js using the concat() method, or you can refer below method.

Using the spread operator method

The spread operator was added from the ES6 version (ES2015) and the rest parameter. These two types of operators are syntactically similar, using the same …

Uses of spread operator:

  • Copy an array
  • Split or combine one or more arrays
  • Use array as a list of arguments
  • Add an item to a list
  • Manipulating state in React
  • Combine objects
  • Convert NodeList to an array

So you can use the spread operator to concatenate two arrays because its essence is to get all the elements in the array using this method. And we will create a new array to hold both of these arrays, and we will have a new merged array.

Code:

 import { useState } from "react";
 
 export default function App() {
  var array1 = ["one", "two"];
  var array2 = ["three", "four", "five"];
  const [mergeArray,setMergeArray]=useState([...array1,...array2])
  return (
    <div>
      <h2>How to merge two Arrays in React.js | LearnShareIT</h2>
      <p>{JSON.stringify(mergeArray)}</p>
    </div>
  );
}

So we need to add the [] at the ends of the arrays to merge the used spread operator to create a new array to contain them. The results returned by the two methods are the same.

Summary

This article showed you how to merge two arrays in React.js. However, we encourage you to use the concat() method to do this neatly. Let’s try it.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *