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:
- First, we define two lists
array1
andarray2
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];
- Then, we use the
toSet()
method to convert botharray1
andarray2
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()
- Once we have the sets, we use the
intersection
method to find common elements. Theintersection
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())
- We convert back the set to the List using
toList()
.
array1.toSet().intersection(array2.toSet()).toList()
-
We then print the common elements.
-
When we run the code, it outputs
[2, 4, 5]
which are the common elements betweenarray1
andarray2
.
And that’s it! You’ve successfully found common elements in two arrays in Dart.