Reputation: 804
I have two lists and I want to make a new list by comparing the two lists and the new list should only contain those elements that contain in each of them.
List1=[[id: 1, label: 'cocoa'],[id: 2, label: 'apple'],[id: 3, label: 'cherry'],[id: 4, label: 'banana'],[id: 5, label: 'melon'],[id: 6, label: 'orange'],[id: 7, label: 'pineapple'],[id: 8], label: 'strawberry']
List2=[2,5,7,8]
expectedList = [[id: 2, label: 'apple'],[id: 5, label: 'melon'],[id: 7, label: 'pineapple'],[id: 8], label: 'strawberry']]
And the real code down below:
"options": [
{
"id": 58,
"label": "cocoa",
"swatch_value": null,
"products": [
118
]
},
{
"id": 59,
"label": "dark chocolate",
"swatch_value": null,
"products": [
120,
127
]
},
{
"id": 60,
"label": "apple",
"swatch_value": null,
"products": [
121,
128
]
},
{
"id": 61,
"label": "milk",
"swatch_value": null,
"products": [
122
]
},
{
"id": 62,
"label": "coconut",
"swatch_value": null,
"products": [
130
]
},
{
"id": 65,
"label": "cherry",
"swatch_value": null,
"products": [
126
]
}
]
So the first list would contain the json above, and the second list contains the numbers below that equals to some of the ID.
List<int> secondList = [58, 59, 60, 61];
Now when I want to generate a new list by comparing the secondList with the ID's of the first list, the third list is empty.
List thirdList = firstList.options.where((element) => secondList.contains(element.id)).toList();
Upvotes: 0
Views: 2766
Reputation: 6257
var list1 = [1,2,3,4,5,6,7,8];
var list2 = [2,5,7,8];
var expectedList = list1.toSet().intersection(list2.toSet()).toList();
print(expectedList.toString());
More information here.
Respect to your info:
var dataList = data['options'];
var firstList = List<int>.generate(dataList.length, (i) => dataList[i]['id']);
var secondList = [58, 59, 60, 61];
var thirdList = firstList.toSet().intersection(secondList.toSet()).toList();
var filtered = dataList.where((e) => thirdList.contains(e['id'])).toList();
print(filtered.toString());
where:
const data = {
"options": [
...
]
};
The result is:
[{id: 58, label: cocoa, swatch_value: null, products: [118]}, {id: 59, label: dark chocolate, swatch_value: null, products: [120, 127]}, {id: 60, label: apple, swatch_value: null, products: [121, 128]}, {id: 61, label: milk, swatch_value: null, products: [122]}]
Upvotes: 3