I have the following example array of objects, each object in the array contains an id, personId, scores and finally score. In some objects the scores is either null or it contains another array of objects which are the scores. In other objects the score may contain a value instead of being null. Finally, there may be a case when the object can contain both scores and score.
const startingArray = [
{
id: 1,
personId: 1,
scores: [
{
id: 1,
title: 'Google',
score: 12
},
{
id: 2,
title: 'Bing',
score: 23
},
{
id: 3,
title: 'Facebook',
score: 34
}
],
score: null
},
{
id: 2,
personId: 1,
scores: null,
score: 123
},
{
id: 3,
personId: 2,
scores: [
{
id: 4,
title: 'Google',
score: 7
},
{
id: 5,
title: 'Bing',
score: 32
},
{
id: 6,
title: 'Facebook',
score: 9
}
],
score: null
},
{
id: 4,
personId: 3,
scores: null,
score: 106
},
{
id: 5,
personId: 3,
scores: [
{
id: 7,
title: 'Google',
score: 6
},
{
id: 8,
title: 'Bing',
score: 4
},
{
id: 9,
title: 'Facebook',
score: 3
}
],
score: 5
}
]
I can filter the startingArray to return the valid objects for a person:
startingArray.filter(item => item.personId === personId)
And I also figured out how to use map and reduce to return a value of the score items for the person:
startingArray.filter(item => item.personId === personId).map(item => item.score).reduce((a, b) => a + b, 0)
Where I'm struggling is to be able to sum the score items in the scores array where it's set against a person.
Ultimately what I'm after is to be able to call personScores(1) and it return the total of the scores for person 1 (i.e. 69), or call personScores(3) and it would return 124 (i.e. 106 + 13 + 5).
findinstead offilter. Then you'll get a single person object (or null) whose.scoresyou can access and reduce, not an array of (a single) persons.personScores(5)?id:2also hadpersonId:1, so that would result in69+123=192. Thanks for pointing that out :)