Home > Enterprise >  Problem while filtering one array based on values in second array in Vue.js
Problem while filtering one array based on values in second array in Vue.js

Time:09-20

I have a problem filtering the data array. I have two arrays: families and children. And I can't figure out how I could filter the array according to the age field in the children's array. I already translate: The common thing between these data arrays is the family_id field. My code looks like this:

filterProductsByYear: function(families) {
    return families.filter(
        family => family.family_id.includes(this.children.family_id)
    );
},

And how could I filter a families array of data by the age of children array about the children_year field?

I wonder if adding a where clause in this includes make sense, I thought it was the best idea, but I don't know how can I do it.

CodePudding user response:

You should provide an in and output example in your question, or we have to make many assumptions about the data structure. You could try the following. It returns all the families with at least one child under 18:

familiesWithAdolescentChildren: function(families, children) {
    return families.filter(
        family => children.some(
         child => child.family_id == family.id && child.age > 18)
        )
    );
},

Example:
in:
familes: [{id: 1}, {id: 2}]
children: [{family_id: 1, age: 3}, {family_id: 1, age: 21}, {family_id: 2, age: 20}]

out:
[{id: 1}]

  • Related