Karel Debedts
Karel Debedts

Reputation: 5758

Dart: 2 lists, show elements of list a that aren't in list b

I'm trying to compare 2 lists. (Dart (flutter))

List a = [1,2,3,4]
List b = [2,3]

I want to find the elements of List a that aren't in List b. Outcome:

List c = [1,4]

Which method should I use? From math at school, I know you can use intersection to find the communal elements, but don't know the name for this 'method'.

Thanks in advance!

Upvotes: 2

Views: 722

Answers (1)

kaya3
kaya3

Reputation: 51037

This is much easier if you use sets instead of lists: the Set.difference method does exactly this.

Alternatively, if you want the output to be a list (to maintain the ordering from list a), the most efficient way is still to store the elements from list b in a set, then use a loop over list a to build the list c out of the elements which aren't in set b, using the Set.contains method.

Upvotes: 2

Related Questions