Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
705 views
in Technique[技术] by (71.8m points)

flutter - Compare 2 different list and filter the first list

Trying to achieve the below result but not able to find the correct process or code to resolve it. Please find any solution.

List ids = ['2330', '1111'];
List users = [{"id": ['1234','2330'], "name": "username1"}, {"id":['1111','2330'], "name": "username2"},{"id": ['3455','2331'], "name": "username3"}];
# I want the result to be like
List selectedUsers = [{"id": ['1234','2330'], "name": "username1"}, {"id":['1111','2330'], "name": "username2"}];

I tried this...

 List selectedUsers = users.where((u) => ids.contains(u["id"])).toList();

But that doesn't work...

 Result: []

What am I doing wrong?

Thanks in advance!

question from:https://stackoverflow.com/questions/65833919/compare-2-different-list-and-filter-the-first-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your code is slightly wrong. You are checking if ids contains the whole list u["id"].

Try this:

List selectedUsers = users.where((u) => ids.any((id) => u["id"].contains(id))).toList();

ids.any(...) takes a function as a test and returns true if any element of the iterable ids passes the test. Here, your test should return true if any of the id from ids appear in u["id"]. Now using this whole thing as your filter, you get the desired result:

[{id: [1234, 2330], name: username1}, {id: [1111, 2330], name: username2}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...