Skip to content

Instantly share code, notes, and snippets.

@masa7351
Last active July 14, 2021 18:08
Show Gist options
  • Save masa7351/17c16bd9750fe08793213090d7f6222d to your computer and use it in GitHub Desktop.
Save masa7351/17c16bd9750fe08793213090d7f6222d to your computer and use it in GitHub Desktop.
オブジェクト型の配列の重複した要素を削ったものがほしかったので作成
List<S> dedupe<T, S>(List<S> values, T Function(S) key) {
var valuesSet = <T>{};
List<S> results = [];
for (var element in values) {
if (!valuesSet.contains(key(element))) {
valuesSet.add(key(element));
results.add(element);
}
}
return results;
}
void main() {
final List<Hoge> hogeList = [Hoge(id: "1", body:"テキスト1"),
Hoge(id: "2", body:"テキスト2"),
Hoge(id: "3", body:"テキスト3"),
Hoge(id: "4", body:"テキスト4"),
Hoge(id: "5", body:"テキスト5")];
final List<Hoge> addList = [Hoge(id: "2", body:"テキスト2"),
Hoge(id: "3", body:"テキスト3"),
Hoge(id: "6", body:"テキスト6"),
Hoge(id: "7", body:"テキスト7")];
// 2つの配列を結合
hogeList.addAll(addList);
final dedupeList = dedupe(hogeList, (Hoge element) => element.id);
print(dedupeList);
}
class Hoge {
String id;
String body;
Hoge({required this.id, required this.body});
@override
String toString() {
return 'Hoge: {id: ${id}, body: ${body}}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment