Reputation: 97
I have an array of objects containing more objects.
const latestMatchesArray = [
{
team1: {
team_id: '1234',
teamName: 'abc 101',
score: 1,
},
team2: {
team_id: '4321',
teamName: 'cba 101',
score: 0,
},
},
{
team1: {
team_id: '1234',
teamName: 'abc 101',
score: 0,
},
team2: {
team_id: '4321',
teamName: 'cba 101',
score: 1,
},
},
]
Each object contains a match between two teams, after the match, the scores are updated. Winner gets 1, loser gets 0.
Now I want to filter the array and get only teams with score = 1.
How to do this efficiently?
Upvotes: 1
Views: 30
Reputation: 22775
Not sure if this is what you're looking for, but to get an array of teams that won, you can use Array.prototype.reduce()
like this:
const winners = latestMatchesArray.reduce(
(teams, match) => [
...teams,
...[match.team1, match.team2].filter(
team => team.score === 1
)
],
[]
);
Upvotes: 2