Daniel Sogbey
Daniel Sogbey

Reputation: 323

How do I compare two List<Map> types to identify the matching and non matching items

What I want is to get all the matching and non matching items from two List types in dart. So supposing I have a List a and List b, how do I obtain a difference say List c.

Below is a representation of my current problem.

 var a = [
{"id":"1","b":"2"},
{"id":"2","d":"4"},
{"id":"3","f":"6"}
]; 

 var b = [
{"id":"1","b":"2"},
{"id":"3","f":"6"}
];

How do I obtain a difference of List c :

c = [{"id":"2","d":"4"}]

Upvotes: 0

Views: 1058

Answers (3)

Randal Schwartz
Randal Schwartz

Reputation: 44111

You have two lists of maps that you want to take the difference of. The quickest solution is to turn the two lists into Sets of immutable Maps which can be properly used as Set keys, then take the Set difference. Like this:

import 'package:fast_immutable_collections/fast_immutable_collections.dart';

void main(List<String> arguments) {
  final a = [
    {"id": "1", "b": "2"},
    {"id": "2", "d": "4"},
    {"id": "3", "f": "6"}
  ];

  final b = [
    {"id": "1", "b": "2"},
    {"id": "3", "d": "6"}
  ];

  final aSet = a
      .map(
        (e) => IMap(e),
      )
      .toSet();
  final bSet = b
      .map(
        (e) => IMap(e),
      )
      .toSet();

  print(
    aSet.difference(bSet).toList(),
  );
}

This results in:

[{
   id: 2,
   d: 4
}, {
   id: 3,
   f: 6
}]

Which seems to be what you wanted.

Update: not quite. You didn't specify what happens with {"id":"3","d":"6"}. I include it as a difference of these sets. You'll need to clarify your problem.

Upvotes: 1

Manpreet Singh Pandher
Manpreet Singh Pandher

Reputation: 257

you can compare as below:

for non-matching record as:

  var c= a.where((e)=>b.where((ee)=>e['id']==ee['id']).toList().isEmpty).toList();

for matching record as:

 var c= a.where((e)=>b.where((ee)=>e['id']==ee['id']).toList().isNotEmpty).toList();

Upvotes: 1

Wiktor
Wiktor

Reputation: 775

I am not sure if I've understood it well, but this would be my first approach. Time complexity isn't the best, it probably can be optimized. I may try to do it when I'll be sure it is what you're looking for.

typedef mapList = List<Map<String, String>>;

mapList substractMaps(mapList a, mapList b) {
  mapList difference = [];
  a.forEach((aMap){
    final currentIdValue = aMap['id'];
    bool found = false;
    b.forEach((bMap) {
      if(bMap['id'] == currentIdValue) {
        found = true;
      }
    });
    if(!found) {
      difference.add(aMap);
    }
  });
    
 return difference;
}

Upvotes: 1

Related Questions