Search code examples
javascriptarraysloopsforeachfrequency

Check frequence of ocurrences in each subitem in an array


I have an array that returns something like:

const arr = [
    {
        "id": "5ac2f57f-61cf-454b-9457-484b8484c1d3",
        "userID": "7d21e968-f32a-4cb9-a0db-dd98d1d2973a",
        "tag": "REPORT_CREATE",
    },
    {
        "id": "3d302f03-75da-40cf-8b86-d9673fdc3b4a",
        "userID": "1dafdb46-a49e-4194-9e5b-9c44be7e4cda",
        "tag": "REPORT_CREATE",
    },
]

And i need to return the frequence of the "userID", but as you can see, it is a subitem.

So if i do something like:

function getOccurrence(array, value) {
   var count = 0;
   array.forEach((v) => (v === value && count++));
   return count;
}

console.log(getOccurrence(arr, "userIDsomething"));

That wouldn't do cause the userID would have to be the objects itself, not inside [0], [1] and so on. But i am stuck there. Any suggestions?


Solution

  • You just need to compare value against the userID property of the items in your array, rather than against the items themselves. Also, it might simplify your code to use filter.

    Try this:

    function getOccurrence(array, value) {
       return array.filter((v) => v.userID === value).length;
    }