Home > OS >  Dart How to combine Two Arrays based on ID?
Dart How to combine Two Arrays based on ID?

Time:02-26

i have list like below

     var list1=[
      {"id": "10", "name": "item1"},
      {"id": "20", "name": "item2"},
      {"id": "30", "name": "item3"},
      {"id": "40", "name": "item4"}];

var list2=[
      {"id": "10", "qty": 20},
      {"id": "20", "qty": 12},     
      {"id": "40", "qty": 10}];

i want new list like

List<Map<String,dynamic>> list3= [
          {"id": "10", "name": "item1","qty": 20},
          {"id": "20", "name": "item2","qty": 12},
          {"id": "30", "name": "item3","qty": 0},
          {"id": "40", "name": "item4","qty": 10}];

how to do this need help..

CodePudding user response:

You can use a for loop to achieve the scenario. I know I am going old school by using for loop, there might be much simpler ways as well. But, anyways, this is what I came up with.

  void main(){

  List <Map<String,dynamic>> list1 = [
      {"id": "10", "name": "item1"},
      {"id": "20", "name": "item2"},
      {"id": "30", "name": "item3"},
      {"id": "40", "name": "item4"}];

  List <Map<String,dynamic>> list2 = [
      {"id": "10", "qty": 20},
      {"id": "20", "qty": 12},     
      {"id": "40", "qty": 10}];
  
  List <Map<String,dynamic>> list3 = [];
  
  // for loop that does all the work
  for(int i = 0; i < list1.length; i  ){
    for(int j = 0; j < list2.length; j  ){
      if (list1[i]["id"] == list2[j]["id"]){
        list1[i]["qty"]= list2[j]["qty"];
        list3.add(list1[i]);
        break;
      }
      else if (j == list2.length - 1){
        list1[i]["qty"] = 0;
        list3.add(list1[i]);
      }
    }
  }
  print(list3);
}

Result:

[{id: 10, name: item1, qty: 20}, {id: 20, name: item2, qty: 12}, {id: 30, name: item3, qty: 0}, {id: 40, name: item4, qty: 10}]

CodePudding user response:

Here is one possible solution.

This solution assumes that

  • list1 will not have more than one element with the same id
  • list2 will not have more than one element with the same id
  • all of the ids can be found in list1 but not necessarily list2 (no id 30 in list2)
void main() {
  var list1 = [
    {"id": "10", "name": "item1"},
    {"id": "20", "name": "item2"},
    {"id": "30", "name": "item3"},
    {"id": "40", "name": "item4"},
  ];

  var list2 = [
    {"id": "10", "qty": 20},
    {"id": "20", "qty": 12},
    {"id": "40", "qty": 10},
  ];

  List<Map<String, dynamic>> list3 = [
    for (final item1 in list1)
      {
        ...item1,
        ...list2.firstWhere(((item2) => item1['id'] == item2['id']),
            orElse: () => {'qty': 0}),
      },
  ];

  print(list3);
}

CodePudding user response:

final result = list1.map((item1) { 
  return {
    ...item1, 
    ...list2.firstWhere((item2) => item1["id"] == item2["id"], orElse: () => {"qty": 0})
  }; 
}).toList();
  • Related