Search code examples
arraysballerinaballerina-swan-lake

How to join merge/join two arrays in ballerina


Lets say I have two int arrays.

  1. How can I merge these two arrays?
  2. How can I create a new array out of these two arrays?

Solution

    1. To merge one array to another array, use array push function.
    2. To merge two arrays and create a new array, use spread operator.

    Sample code can be found in the below snippet.

    import ballerina/io;
    
    public function main() {
        int[] x = [1, 2];
        int[] y = [3, 4, 5];
        int[] z = [6, 7, 8];
    
        // Answer to Q1.
        // Pushes all of the members in `y` to x
        x.push(...y);
        // `x` changes now.
        io:println(x); // [1,2,3,4,5]
        // `y` remains the same.
        io:println(y); // [3,4,5]
    
        // Answer to Q2.
        // Creates a new list with the members from `x` and `y`.
        int[] arr = [...x, ...z];
        io:println(arr); // [1,2,3,4,5,6,7,8]
    
        io:println(x); // [1,2,3,4,5]
        io:println(y); // [3,4,5]
        io:println(z); // [6, 7, 8]
    }