0

Say you have to find out the names of the students that are in both teamBlue & teamRed

Suppose that the arrays are of unequal length as shown below, how would you go about approching this.
if someone could just point me in the right direction id really appreciate it

teamRed: [
    {
        "id": '1',
        "name": "jenny"
    },
    {
        "id": '2',
        "name": "kenny"
    },
    {
        "id": '3',
        "name": "mike"
    },
     {
        "id": '4',
        "name": "danny"
    }
]


teamBlue: [
    {
        "id": '1',
        "name": "joey"
    },
    {
        "id": '2',
        "name": "kenny"
    },
    {
        "id": '3',
        "name": "mike"
    }
]
1

1 Answer 1

2

You can do that simply using Array.forEach() and Array.find.

Here is a simple example:

const teamRed = [ ... ]
const teamBlue = [ ... ]
const studentsInBothTeams = []

teamRed.forEach(_teamRed => {
  const existsOnTeamBlue = teamBlue.find(
    _teamBlue => _teamBlue.name === _teamRed.name
  )

  if (existsOnTeamBlue) {
    studentsInBothTeams.push(_teamRed)
  }
})

console.log(studentsInBothTeams)

The result is:

[
  {
    "id": "2",
    "name":"kenny"
  },
  {
    "id": "3",
    "name": "mike"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.