Ad

How To Remove Object In List Of Map If One Of Map Value Is The Same With Other Map

- 1 answer

so i have list of maps with 'name' and 'place' value, the case is if map one and map two 'place' value is the same i want map two to be deleted. With my exampleList we can see that map one with name of akashi and place Japan then map two have name Genta and place Japan too, i want to delete map two because the place is same as map one.

List exampleList = [
    {
      'name': 'Akashi',
      'place': 'Japan',
    },
    {
      'name': 'Genta',
      'place': 'Japan',
    },
    {
      'name': 'Hinata',
      'place': 'indonesia',
    },
    {
      'name': 'Jinwoo',
      'place': 'Korea',
    },
  ];
Ad

Answer

You can define a List<String> to store the unique places and just use it to check if the place is already exist or not.

Here is a complete function to filter with the required logic:

List filterList(List list, {bool removeAllOccurrences = false}) {
  final List<String> uniquePlaces = [];
  final List filteredList = [];

  for (Map map in list) {
    if (!uniquePlaces.contains(map['place'])) {
      // If it is the first time to see this place

      uniquePlaces.add(map['place']);

      filteredList.add(map);
    } else {
      if (removeAllOccurrences) {
        filteredList.removeWhere((m) => m['place'] == map['place']);
      }
    }
  }

  return filteredList;
}

And here is the output of the function performed on your example list:

Keeping only one occurrence:
[{name: Akashi, place: Japan}, {name: Hinata, place: indonesia}, {name: Jinwoo, place: Korea}]

Removing all occurrences:
[{name: Hinata, place: indonesia}, {name: Jinwoo, place: Korea}]

You can also check this link to get a working example at DartPad.

Ad
source: stackoverflow.com
Ad