Home > Software engineering >  how to remove object in list of map if one of map value is the same with other map
how to remove object in list of map if one of map value is the same with other map

Time:08-05

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',
    },
  ];

CodePudding user response:

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) {
  final List<String> uniquePlaces = [];
  final List filteredList = [];

  for (Map map in list) {
    if (!uniquePlaces.contains(map['place'])) {
      uniquePlaces.add(map['place']);

      filteredList.add(map);
    }
  }

  return filteredList;
}

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

[{name: Akashi, place: Japan}, {name: Hinata, place: indonesia}, {name: Jinwoo, place: Korea}]

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

CodePudding user response:

Check LodashFlutter package, In package declare various method it's much helpful for you.

You have to use only single line code and you get your results.

  • uniqBy(List array, key);

  • uniq(List array);

https://pub.dev/packages/lodash_flutter

  • Related