How can we concatenate or merge two arrays in Scala?

Overview

We can use the concat() method of the array class to concatenate or merge two arrays . This method takes two arrays and combines them to form a single array.

Syntax

Array.concat(array1, array2)
Syntax of the "concat()" method

Parameter values

array1: This is one of the two arrays that we want to merge.

array2: This is the second of the two arrays that we want to merge.

Return value

The concat() method returns a new array that concatenates the arrays array1 and array2.

Example

object Main extends App {
// create some arrays
val randomNumbers1 = Array(34, 2, 5, 70, 1)
val randomNumbers2 = Array(9, 40, 3, 0)
val fruits1 = Array("Pineapple", "Banana", "Orange")
val fruits2 = Array("Apple", "Water-melon")
val cgpas1 : Array[Double] = Array(3.4, 4.5, 2.5, 0.5)
val cgpas2 : Array[Double] = Array(5.0, 1.5)
// concat arrays
val randomNumbers = Array.concat(randomNumbers1, randomNumbers2)
val fruits = Array.concat(fruits1, fruits2)
val cgpas = Array.concat(cgpas1, cgpas2)
// print concated array
print(randomNumbers.mkString(" "))
print("\n"+fruits.mkString(" "))
print("\n"+cgpas.mkString(" "))
}

Explanation

  • Lines 3–8: We create several arrays and initialise them with some values.
  • Lines 11–13: We concatenate or merge the arrays using the concat() method. Then, we store the returned results in a new array variable.
  • Lines 16–18: We convert the arrays to strings using the mkString() method. Then, we print the strings to the console.