Home > Net >  Dart : Compare between different type of list
Dart : Compare between different type of list

Time:08-25

I have two type of list. Here,

List list1= [
  {"id": "3", "topic_name": "Studying In Bangladesh"},
  {"id": "4", "topic_name": "Studying In Sweden"},
  {"id": "6", "topic_name": "Studying In Germany"},
];

List list2 = [
  "2",
  "3",
  "5",
  "6",
];

I want to generate a new topic list from list1, which is matched by list2's elements ( with list1's id ).

Is there any method are available for dart ?

CodePudding user response:

You can do this:

List list3 = list1.where((e) => list2.contains(e['id'])).toList();

CodePudding user response:

You can compare list1's id element with the list 2 with the foreach property in list for iterate through all elements of the list

CodePudding user response:

You can simply map the list1 into new list with the required data:

Example:

void main() {
  List list1= [
    {"id": "3", "topic_name": "Studying In Bangladesh"},
    {"id": "4", "topic_name": "Studying In Sweden"},
    {"id": "6", "topic_name": "Studying In Germany"},
  ];

    final list2 = list1.map((e)=> e['id']).toList();

    print(list2);
  }

Output:

[3, 4, 6]
  • Related