OneBite.Dev - Coding blog in a bite size

Merge Multiple Array In Dart

Code snippet for how to Merge Multiple Array In Dart with sample and detail explanation

Dart is a general-purpose programming language designed for client development. One common task you might come across while working in Dart is merging multiple arrays. In this article, we are going to see how to accomplish this task simply and effectively.

Code snippet: Merging Multiple Arrays

In Dart, we can merge arrays using the plus (+) operator or the addAll() function. Here is a short code snippet on how to get this done:

void main() {
   List<int> arr1 = [1, 2, 3];
   List<int> arr2 = [4, 5, 6];
   List<int> arr3 = [7, 8, 9];
   List<int> mergedArray = [];

   mergedArray = arr1 + arr2 + arr3;

   print(mergedArray);
}

Or using the addAll() function:

void main() {
   List<int> arr1 = [1, 2, 3];
   List<int> arr2 = [4, 5, 6];
   List<int> arr3 = [7, 8, 9];
   List<int> mergedArray = [];

   mergedArray.addAll(arr1);
   mergedArray.addAll(arr2);
   mergedArray.addAll(arr3);

   print(mergedArray);
}

In both methods, the output will be: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Code Explanation: Merging Multiple Arrays

The Dart code for merging arrays is quite simple. First, we declare and initialize three different lists named arr1, arr2, and arr3. Next, we declare an empty list called mergedArray.

In the first method, we use the plus operator (+) to concatenate the three arrays (lists). arr1, arr2, and arr3 are added together using the plus operator and the result is assigned to mergedArray. This will combine all the elements from all three arrays into one.

In the second method, instead of using the plus operator, we use the addAll() function. This function is a method provided by the Dart List class to add all elements of a given iterable to the end of a list. We call addAll() on the mergedArray and pass the array that we want to add as the argument. We do this for all the arrays that we want to merge.

After merging, we output mergedArray which will now contain all the elements from arr1, arr2, and arr3.

In both cases, the resulting merged array will be [1, 2, 3, 4, 5, 6, 7, 8, 9]. Clearly, both methods are quite straightforward and simple, but the first method with the plus operator is a little more concise.

dart