DEV Community

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

Posted on

4

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 😊

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay