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: "benshekhtman@hotmail.com"
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: "benshekhtman@hotmail.com"
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: "test@email.com"
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 :
in your line
s.located_at.some((location) => location.id === client.location_id)
you have forgotten to return the results.
just change to
return s.located_at.some((location) => location.id === client.location_id)
const client = {
location_id:7
}
const staff = [{
contact_number: "4168455302",
email: "benshekhtman@hotmail.com",
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: "test@email.com",
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",
}]
const filterStaffByLocation = staff.filter((s) => {
return s.located_at.some((location) => location.id === client.location_id)
})
console.log(filterStaffByLocation)
.as-console-wrapper { max-height: 100% !important; top: 0; }