Reputation: 2023
I have the list of convention below, i want to filter this list by specialty, ie when i enter 15 it return the conventions with id 1 and 2
[
{
"id": 1,
"typeActivities": [
{
"id"=11,
"specialitiesId": [10, 15]
}
]
},
{
"id": 2,
"typeActivities": [
{
"id"=22,
"specialitiesId": [10]
},
{
"id"=222,
"specialitiesId": [15]
}
]
},
{
"id": 3,
"typeActivities": [
{
"id"=33,
"specialitiesId": [12]
}
]
}
]
i tried with this function but is return nothing
let input: number = 15;
let convention: Convention[];
convention = this.conventions.filter(convention => {
let typeActivities: TypeActivity[] = convention.typeActivities.filter(typeActivitiy => {
if (typeActivitiy.specialitiesId) {
return input == typeActivitiy.specialitiesId.find(id => id == input);
}
});
//console.log(convention.typeActivities.map(i => i.id).filter(item => typeActivities.map(i => i.id).indexOf(item) >= 0));
});
Upvotes: 2
Views: 140
Reputation: 1075655
Array#some
is really useful for things like this:
let input: number = 15;
let convention: Convention[];
convention = this.conventions.filter(convention =>
convention.typeActivities.some(activity =>
activity.specialitiesId.some(e => e == input)
)
);
convention.typeActivities.some(...)
will call its predicate with each entry until it runs out (some
returns false
) or the predicate returns a truthy value (some
returns true
); the same with activity.specialitiesId.some(...)
.
Live JavaScript example:
const example = {
conventions: [
{
"id": 1,
"typeActivities": [
{
"id": 11,
"specialitiesId": [10, 15]
}
]
},
{
"id": 2,
"typeActivities": [
{
"id": 22,
"specialitiesId": [10]
},
{
"id": 222,
"specialitiesId": [15]
}
]
},
{
"id": 3,
"typeActivities": [
{
"id": 33,
"specialitiesId": [12]
}
]
}
],
find(input) {
let convention;
convention = this.conventions.filter(convention =>
convention.typeActivities.some(activity =>
activity.specialitiesId.some(e => e == input)
)
);
return convention;
}
};
console.log(example.find(15));
.as-console-wrapper {
max-height: 100% !important;
}
Upvotes: 5