I have a large array (list of dictionaries) in javascript and I have to retrieve data from the array in a specific format here is an example of a snippet of the array
data = [{"userId":1, "completed":true},
{"userId":1, "completed":false},
{"userId":1, "completed":true},
{"userId":2, "completed":false},
{"userId":2, "completed":true}
]
what I had to do was retrieve the userId and the count of (completed) if its value is true
eg ouput = {1, 2} for userId:1
i tried filtering and looping but it doesn’t seem to work
2
Answers
Sounds like you might want to user reduce and group them by userId. So maybe this:
Use the
forEach
method to loop through the array. For each object, it checks ifcompleted
value istrue
, and if so, increments the count for the correspondinguserId
in theuserCounts
object. The resultinguserCounts
object contains the counts of completed tasks for each user wherecompleted
is true.You can make it a bit shorter, basically an arrow function expression.