kmtz
kmtz

Reputation: 544

Check if two lists have any element in common

How to add to list1 element(s) from list2 where value for type key is not the same?

  var list1 = <Map<String, String>>[
    {'id': '123', 'type': 'START', 'location': 'Vienna'},
  ];

  var list2 = <Map<String, String>>[
    {'type': 'START'},
    {'type': 'STOPOVER'},
    {'type': 'DESTINATION'},
    {'type': 'END'}
  ];

So list1 should look like this at the end:

  list1 = <Map<String, String>>[
    {'id': '123', 'type': 'START', 'location': 'Vienna'},
    {'type': 'STOPOVER'},
    {'type': 'DESTINATION'},
    {'type': 'END'}
  ];

Upvotes: 2

Views: 1086

Answers (2)

Laszlo Treszkai
Laszlo Treszkai

Reputation: 400

In a more imperative style:

var result = <Map<String, String>>[];

for (var x2 in list2) {
    final x1s_like_x2 = list1.where((x1) => x1['type'] == x2['type']);
    if (x1s_like_x2.isEmpty) {
        result.add(x2);
    } else {
        result.addAll(x1s_like_x2);
    }
}

Then you'll have the merged list in result.

Upvotes: 1

user18309290
user18309290

Reputation: 8300

list1.addAll(
    list2.where((item) => list1.where((item2) => item['type'] != item2['type']).isNotEmpty)
);

Upvotes: 1

Related Questions