Skip to content

Instantly share code, notes, and snippets.

@kishan-dhankecha
Last active October 12, 2021 16:00
Show Gist options
  • Save kishan-dhankecha/07c94adb68d3d01d92dc40dbd23461be to your computer and use it in GitHub Desktop.
Save kishan-dhankecha/07c94adb68d3d01d92dc40dbd23461be to your computer and use it in GitHub Desktop.
Get new List with id and number of times object repeats in a List with dart.
String checkCountOf = 'id';
List objects = [
{"id": "123"},
{"id": "123"},
{"id": "20"},
{"id": "35"},
{"id": "20"},
];
void main() {
var output = [];
for (final obj in objects) {
var index = output.indexWhere((e) {
return e[checkCountOf] == obj[checkCountOf];
});
if (index >= 0) {
output[index]['count']++;
} else {
output.add({
checkCountOf: obj[checkCountOf],
"count": 1,
});
}
}
print(output);
// [{id: 123, count: 2}, {id: 20, count: 2}, {id: 35, count: 1}]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment