'Filter an array to return matching id's of a nested array in JavaScript [duplicate]

I have a client object with a location_id of 1 for example.

and an array of staff. Each staff member contains a nested array of location_ids. I want to filter the staff array to return all the staff members that have a matching id entry in their located_at array to the same location_id as the client.

a staffMember obj looks as so:

contact_number: "4168455302"
email: "[email protected]"
first_name: "Ben"
id: 2
last_name: "Shekhtman"
located_at: [
  {id: 1, name: "Ben's Location"}
  {id: 2, name: 'My second location'}
  {id: 7, name: 'Medicare Clinic'}
]

here is my attempted logic:

  const filterStaffByLocation = staff.filter((s) => {
    s.located_at.some((location) => location.id === client.location_id)
  })

currently filterStaffByLocation is returning an empty []

more details: If the staff array looks as so:

[{
contact_number: "4168455302"
email: "[email protected]"
first_name: "Ben"
id: 2
last_name: "Shekhtman"
located_at: [
  {id: 1, name: "Ben's Location"}
  {id: 2, name: 'My second location'}
  {id: 7, name: 'Medicare Clinic'}
]
provider_id: 2
user_id: 2
user_type: "ADMIN"
},
{
contact_number: "9053700017"
email: "[email protected]"
first_name: "Test "
id: 3
last_name: "Team Member"
located_at: [
 {id: 3, name: 's'}
 {id: 7, name: 'Medicare Clinic'}
]
provider_id: 2
user_id: 7
user_type: "SUPPORT"
}]

testing against a client location_id of 1 should only return the first entry (staffMember with id of 2)



Solution 1:[1]

Hopefully I understood what you wanted. But heres how to do it below


/*
   Return all staff that have the location_id passed in
*/
const staffAtUserId = (staffArray,id)=>{
   // List to return 
   const retArr = []
   // Loop through all staff
   staffArray.forEach(staff=>{
       // Check if staff has that id in there location
       const hasLocationId = staff.located_at.some(obj=>obj.id===id)
       // If true at to return list
       if (hasLocationId){
           retArr.push(staff)
       }
   })
   return retArr
}

const staffArray = [{
    contact_number: "4168455302",
    email: "[email protected]",
    first_name: "Ben",
    id: 2,
    last_name: "Shekhtman",
    located_at: [
      {id: 1, name: "Ben's Location"},
      {id: 2, name: 'My second location'},
      {id: 7, name: 'Medicare Clinic'},
    ],
    provider_id: 2,
    user_id: 2,
    user_type: "ADMIN",
    },
    {
    contact_number: "9053700017",
    email: "[email protected]",
    first_name: "Test ",
    id: 3,
    last_name: "Team Member",
    located_at: [
     {id: 3, name: 's'},
     {id: 7, name: 'Medicare Clinic'}
    ],
    provider_id: 2,
    user_id: 7,
    user_type: "SUPPORT",
}]
console.log(staffAtUserId(staffArray,7))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 carlosdafield