How can I remove duplicate list then get the latest ID?
101
Since what you want is "group by chat_room_id", we need to generate it first from from_id and to_id. I assume your list are already sorted by msg_id. I generate the chat_room_id by joining from_id and to_id after it sorted. The reason why we need to sort them first because from_id 10, to_id 20 is the same chat room as from_id 20, to_id 10.
List<Map> data = [
{"msg_id": 1, "from_id": 10, "to_id": 20, "text": 'Some text123'},
{"msg_id": 2, "from_id": 20, "to_id": 10, "text": 'Some text321'},
{"msg_id": 3, "from_id": 10, "to_id": 20, "text": 'Some text again'},
{"msg_id": 4, "from_id": 5, "to_id": 15, "text": 'Hello World'},
{"msg_id": 5, "from_id": 15, "to_id": 5, "text": 'Hello World'}
];
Map<String, Map> perRoom = {};
data.forEach((d) {
// getting room id
List<int> roomIdList = [d["from_id"], d["to_id"]];
// need to be sorted since from_id 10, to_id 20 is the same room as from_id 20, to_id 10
roomIdList.sort();
String roomId = roomIdList.join('-');
perRoom[roomId] = d;
});
// convert Map<String, Map> back into List<Map>
List<Map> onlyLatest = perRoom.values.toList();
print(onlyLatest);
If your list comes from query, I really recommend you to have chat_room_id in the database since you can just use something like GROUP BY and avoid getting a lot of data from the DB.
Author by
husainazkas
Updated on December 25, 2022Comments
-
husainazkas over 1 year
I have this
List<Map>
:[ {msg_id: 1, from_id: 10, to_id: 20, text: 'Some text123'}, {msg_id: 2, from_id: 20, to_id: 10, text: 'Some text321'}, {msg_id: 3, from_id: 10, to_id: 20, text: 'Some text again'}, {msg_id: 4, from_id: 5, to_id: 15, text: 'Hello World'}, {msg_id: 5, from_id: 15, to_id: 5, text: 'Hello World'} ];
Then I need to get last message by
msg_id
with different chat rooms like this :[ {msg_id: 3, from_id: 10, to_id: 20, text: 'Some text again'}, {msg_id: 5, from_id: 15, to_id: 5, text: 'Hello World'} ];
I've tried
distinct()
andset()
but I still confuse. What should I do?-
DK_bhai over 3 yearsWhat are you considering duplicate here?
-
husainazkas over 3 years@D'Kayd chat room by from_id and to_id
-
-
husainazkas over 3 yearsso we got the room id with String type?
-
Sudhanta Suryaputra over 3 years@husainazkas yess. I can't think another type that more suitable for this. But of course it's up to you how you want to generate the room_id. Just make sure to make both directions (from 10 to 20 and from 20 to 10) generate same room_id