0

I have a list, unfilteredList, with 12 items (messages). As seen in the output, 9 of these messages have the same roomID. My question is then: How can I filter away 8 of these 9 items, such that my list, result, only has 1 of each roomIDs?

I've tried to mess about with for loops and remove an item whenever a second roomID is met. But can't seem to get it working, what am I doing wrong?

List <Inbox> result = [];
int count = 0;
for(int i = 0; i < unfilteredList.length; i++){

  print(i.toString() + '. roomID: ' + unfilteredList[i].roomId);

  result.add(blah[i]);

  for(int j = 0; j < result.length; j++){
    if(result[j].roomId == unfilteredList[i].roomId){
      count++;
      if(count > 1){
        result.removeLast();
        count--;
      }
    }
  }
}

Output from print:

I/flutter (15029): 0. roomID: 1206f5058913246b47f898e7ab7e41ad
I/flutter (15029): 1. roomID: 15b08ee59f29b43d21a24ea6d4071b19
I/flutter (15029): 2. roomID: cd674af0f6048af49bf8222f24bd6103
I/flutter (15029): 3. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 4. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 5. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 6. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 7. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 8. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 9. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 10. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 11. roomID: e5e210a53a3c7e1b03d6cbedbc9da786
I/flutter (15029): 12. roomID: f3f1e4385b36cdd04e10e776220b892e

3 Answers 3

1

You can use a Set to store the unique roomIds. Each time a new id is being added to the set, remove it from the result list if the set already includes it.

final uniqueIds = Set<String>();
result.removeWhere((item) => !uniqueIds.add(item.roomId));
Sign up to request clarification or add additional context in comments.

Comments

0

Well you can just check for the id with .contains() see an output from one of my apps as example:

for (var idx = 0; idx < sampleList.length; idx++){
      if(result.contains(sampleList[idx].userId)){
        print('id exists');
      } else {
        result.add(sampleList[idx].userId);
      }    
    }

It would add the id e5e210a53a3c7e1b03d6cbedbc9da786 the first time and after that skip it.

2 Comments

This was my first attempt actually. Does not work :( Think its because I need "result.add(unfilteredList[i]);" in the else-clause and not "result.add(unfilteredList[i].roomID)"
So I can't really use .containts() in my case, I think :/
0

Use toSet() and then toList().

final uniqueList = results.toSet().toList();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.