OneBite.Dev - Coding blog in a bite size

Find The Unique Elements In Two Arrays In Dart

Code snippet for how to Find The Unique Elements In Two Arrays In Dart with sample and detail explanation

Dart programming language provides helpful methods to manipulate arrays, also known as lists. In this article, we’ll explore how to find the unique elements in two different arrays using the Dart programming language.

Code snippet: Finding Unique Elements in Two Arrays in Dart

Firstly, let’s create two arrays and add some duplicate elements.

void main() {
  var array1 = [1, 2, 3, 4, 5];
  var array2 = [4, 5, 6, 7, 8];
  
  array1.addAll(array2);
  
  var uniqueArray = array1.toSet().toList();
  
  print(uniqueArray);
}

Running this code, our output will be [1, 2, 3, 4, 5, 6, 7, 8], which is a list consisting of all unique elements from the two initial arrays.

Code Explanation: Finding Unique Elements in Two Arrays in Dart

Step 1: Create two Arrays

In Dart, creating an array (or list) is quite straightforward. Here, we’ve created two arrays ‘array1’ and ‘array2’ containing integers.

var array1 = [1, 2, 3, 4, 5];
var array2 = [4, 5, 6, 7, 8];

Step 2: Combine the Arrays

The ‘addAll()’ function is utilized to insert all elements from ‘array2’ into the ‘array1’. This results in one combined array that repeats some numbers.

array1.addAll(array2);

Step 3: Remove Duplicates

To remove duplicate items from the list, we convert the list into a set. A set in Dart, like in many other languages, is a collection of items where every item is unique.

var uniqueArray = array1.toSet().toList();

By converting the list into a set, we effectively remove any duplicates. Afterwards, we convert it back to a list.

When the code is run, it prints out a list of all unique number elements present in the two initial arrays:

print(uniqueArray);

And that’s how you can find the unique elements in two arrays in Dart. You can apply this to different types of elements, not just numbers, as per your specific needs.

dart