I am faced with the challenge of working with 2 arrays in JavaScript. My goal is to identify array objects in the second array that match the Id of an object in the first array and then append these matching objects to the primary object. The additional requirement is to only include the top 3 matching objects based on a certain key value. I attempted this task using Underscore, but it only combined the matching arrays rather than achieving the desired outcome. Any guidance or assistance on how to accomplish the following would be greatly appreciated.
var primaryArray = [
{
"Name": "Main 1",
"Id": "1"
},
{
"Name": "Main 2",
"Id": "2"
}
]
var secondaryArray = [
{
"name": "Person 1",
"mainitemId": "1",
"count": 120
},
{
"name": "Person 2",
"mainitemId": "1",
"count": 80
},
{
"name": "Person 3",
"mainitemId": "1",
"count": 125
},
{
"name": "Person 4",
"mainitemId": "1",
"count": 130
},
{
"name": "Person 5",
"mainitemId": "2",
"count": 90
},
{
"name": "Person 6",
"mainitemId": "2",
"count": 85
},
{
"name": "Person 7",
"mainitemId": "2",
"count": 105
},
{
"name": "Person 8",
"mainitemId": "2",
"count": 110
}
]
var resultArray = [
{
"Name": "Main 1",
"Id": 1,
"people": [
{
"name": "Person 4",
"mainitemId": "1",
"count": 130
},
{
"name": "Person 3",
"mainitemId": "1",
"count": 125
},
{
"name": "Person 1",
"mainitemId": "1",
"count": 120
}
]
},
{
"Name": "Main 2",
"Id": 2,
"people": [
{
"name": "Person 8",
"mainitemId": "2",
"count": 110
},
{
"name": "Person 7",
"mainitemId": "2",
"count": 105
},
{
"name": "Person 5",
"mainitemId": "2",
"count": 90
}
]
}
]