Computer >> Computer tutorials >  >> Programming >> Javascript

How to use spread operator to join two or more arrays in JavaScript?


Two join two or more arrays we have a built-in method called array.concat(). But we can join arrays much more easily by using spread operator.

Syntax

var merged = [...arr1, ...arr2];

Lets' try to merge arrays without spread operator.

In the following example, instead of the spread operator, array.concat() method is used to join two arrays.

Example

<html>
<body>
   <script>
      var arr1 = [1,2,3];
      var arr2 = [4,5,6];
      var merged = arr1.concat(arr2);
      document.write(merged);
   </script>
</body>
</html>

Output

1,2,3,4,5,6

Spread operator 

In the following example, spread operator is used to join two arrays.

Example

<html>
<body>
   <script>
      var arr1 = [1,2,3];
      var arr2 = [4,5,6];
      var merged = [...arr1, ...arr2];
      document.write(merged);
   </script>
</body>
</html>

Output

1,2,3,4,5,6

In the following example, spread operator is used to join 3 arrays. By using concat() method it is difficult if there are more arrays but by using spread operator it is very easy to join more number arrays.

Example

<html>
<body>
   <script>
      var arr1 = [1,2,3];
      var arr2 = [4,5,6];
      var arr3 = [7,8,9];
      var merged = [...arr1,...arr2,...arr3];
      document.write(merged);
   </script>
</body>
</html>

Output

1,2,3,4,5,6,7,8,9