Last active
October 12, 2021 16:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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