DEV Community

loading...
Cover image for How to remove duplicates from an array in Dart

How to remove duplicates from an array in Dart

Ben Matt, Jr.
Lifelong learner
・1 min read

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 😉

Discussion (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. Author

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. Author

Changed thanks 😊