Home > OS >  How to compare Two List of dynamic to identify the matching and non matching records, using the id (
How to compare Two List of dynamic to identify the matching and non matching records, using the id (

Time:08-03

Requirement is to get all the matching and non matching records from the List of Map in dart.

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

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

How do I obtain a difference of :

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

CodePudding user response:

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();

CodePudding user response:

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;
}

CodePudding user response:

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.

  • Related