OneBite.Dev - Coding blog in a bite size

Remove Duplicates From An Array In Dart

Code snippet for how to Remove Duplicates From An Array In Dart with sample and detail explanation

Working with arrays is a fundamental part of any data manipulation task. In this article, we will discuss how to remove duplicates from an array using the Dart programming language.

Code snippet for Removing Duplicates from An Array In Dart

Here is a simple example on how to remove duplicates from an array in Dart:

void main() { 
  var list = [1,2,2,3,3,4,5,5,6,7,7,8,9,9,10]; 
  var uniqueList = list.toSet().toList();
  print(uniqueList);
}

When you run this code, the output will be:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The duplicates in the original array were removed.

Code Explanation for Removing Duplicates from An Array In Dart

The main function begins by declaring a variable “list” that holds an array of integers. This array contains several duplicate entries.

Next, we use two Dart methods to remove the duplicates. First, the toSet() method is used to convert the list to a set.

In Dart, a Set is an unordered collection of unique items. Because a Set only takes unique entries, when we convert our list to a set data structure, all duplicates are automatically removed.

However, since we want our final output in the form of an array (list in Dart terminology), we need to convert the set back to a list. This is achieved through the toList() method, which converts the set back to a list.

Our new list, stored in the variable “uniqueList”, now has all the unique items from the original list, effectively removing all duplicates.

The last line in the function is a print() statement, which will print our new, duplicate-free list in the console. This helps us confirm that our code has worked as expected.

This is how you can employ the Dart language’s inbuilt methods effectively to manipulate arrays and remove duplicate entries. The advantage of this technique is that it is simple, quick and easy to understand, making it suitable for beginners.

dart