DEV Community

Cover image for How to remove duplicates from an array in Dart
Ben Matt, Jr.
Ben Matt, Jr.

Posted on

How to remove duplicates from an array in Dart

removeDuplicates(){
final list = [1, 2, 2, 3, 4, 4, 4];

return list.toSet().toList();
}

Output: [1,2,3,4]

Explanations: First we initialized a variable called list to an array that contains some duplicates, then we converted it to a set(as sets can not contain duplicates) and then back to a list.

Don't forget to follow me if you like tips like this 😉

Top comments (4)

Collapse
 
whoami_ profile image
whoami

simpler
final list = [1, 2, 2, 3, 4, 4, 4].toSet().toList();

Collapse
 
jrmatanda profile image
Ben Matt, Jr.

Yes but for an example doing things step by step is better, for readability.

Collapse
 
whoami_ profile image
whoami

.toList()); ?

Collapse
 
jrmatanda profile image
Ben Matt, Jr.

Changed thanks 😊