rameez khan
rameez khan

Reputation: 359

Flutter find between 2 arrays if match

I have 2 arrays like this

First = [{name: Lab, comments: adsd, id: 5},{name: Lab, comments: rerere, id: 1},{name: Lab, comments: rerere, id: 11}];

second =[{value: 1, label: cholesterol},{value: 5, label: sugar}{value: 10, label: sugar}];

I need to create new array in which if first array id and second array value is same then it will merge and show in new array.

For example i have 3 items in first array i need to match if id of my first array will find in second array so in third array data will be save.

Expected output is final = [{value: 1, label: cholesterol, value: 1, label: cholesterol},{value: 5, label: sugar, name: Lab, comments: adsd, id: 5}];

Upvotes: 0

Views: 1099

Answers (1)

Burak Cabadan
Burak Cabadan

Reputation: 182

you can use where and mapmethods for this.

Edited full code:

void main() {
  List first = [{"name": "Lab", "comments": "adsd", "id": 5},{"name": "Lab", "comments": "rerere", "id": 1},{"name": "Lab", "comments": "rerere", "id": 11}];

   List second =[{"value": 1, "label": "cholesterol"},{"value": 5, "label": "sugar"},{"value": 10, "label": "sugar"}];
  
  
  
  List result = second.where((s) {
    var value = s["value"];
    int index = first.indexWhere((f){
      return  f["id"] == value;
    });
    
    return index != -1;
  }).map((e){
    
    int index = findIndex(first,e);
    
    var data = first[index];
    
    return {
      "value": e["value"],
      "label": e["label"],
      "name": data["name"],
      "comments": data["comments"],
      "id": data["id"],
    };
  }).toList();
  
  print(result);
}

int findIndex(first,s) {
    var value = s["value"];
    int index = first.indexWhere((f){
      return  f["id"] == value;
    });
  return index;
}


What this code does is it iterates through element on the second list, and then searches for id that equals to value in first list, if it cannot find element index will be -1. So we are returning values of second where index not equal to -1.

Upvotes: 1

Related Questions