OneBite.Dev - Coding blog in a bite size

Find The Common Elements In Two Arrays In Dart

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

Finding common elements in two arrays is a common coding challenge. This article will guide you through the process of achieving this in Dart language.

Code snippet for finding common elements in two arrays

Here is a simple dart code snippet to find the common elements in two arrays:

void main() {
  List<int> array1 = [1, 2, 3, 4, 5];
  List<int> array2 = [2, 4, 5, 8, 9];

  List<int> commonElements = array1.toSet().intersection(array2.toSet()).toList();

  print(commonElements);
}

Code Explanation for finding common elements in two arrays

Let’s break the given code snippet down and understand step by step how it works:

  1. First, we define two lists array1 and array2 which contain integer values. These are the two arrays in which we want to find common elements.
List<int> array1 = [1, 2, 3, 4, 5];
List<int> array2 = [2, 4, 5, 8, 9];
  1. Then, we use the toSet() method to convert both array1 and array2 into set. The purpose of this conversion is that set data structure in Dart automatically removes duplicate elements which makes it easier to find common elements.
array1.toSet()
array2.toSet()
  1. Once we have the sets, we use the intersection method to find common elements. The intersection method is a common set operation in Dart that takes one set and returns a new set that contains all the items which are common in both sets.
array1.toSet().intersection(array2.toSet())
  1. We convert back the set to the List using toList().
array1.toSet().intersection(array2.toSet()).toList()
  1. We then print the common elements.

  2. When we run the code, it outputs [2, 4, 5] which are the common elements between array1 and array2.

And that’s it! You’ve successfully found common elements in two arrays in Dart.

dart