Arr1 = [
{
“team”: “bears”,
“coach”, “zeberthal”,
“”quarterback” “mcman”
},
{
“team”: “vikings”,
“coach”, “jones”,
“”quarterback” “cousins”
}
]
]
Arr2 = [“vikings”, “bears”, “packers”, “cousins”, “mcman”]
Some of those values correspond to coach, some are quarterback and some are team. And as you can see sometimes a value is not present (for instance in Arr2 coach is not included). No duplicate values. But sometimes a team may not have a coach or quarterback so that object would have that field as “quarterback”: “” for instance. I would like the filter to return only those values that will return a match (object) if all three fields match or whatever fields there happen to be match. If I only filter for one field no problem:
filteredForFirstValue => arr1.filter(function(result){
return arr2.includes(result.team);
}))
This filters out objects that don’t match the one field result.team but I also need filteredForFirstValue to then be filtered and to return only the objects that match quarterback so something like.
Filter2 = filteredForFirstValue.filter( function(result){
return arr2.includes(result.quarterback);
}))
console.log(filter2)
In React.js this is not working I am getting undefined on my filteredForFirstValue array. Can anyone help me identify my issue?
CodePudding user response:
Define each filter as a function that accepts the array to filter as an argument. Then you can compose them together.
const filter1 = arr => arr.filter(result => arr2.includes(result.team));
const filter2 = arr => arr.filter(result => arr2.includes(result.quarterback));
let res = filter2(filter1(arr1));
CodePudding user response:
You can sum up your criteria
Filter2 = filteredForFirstValue.filter( function(result){
var matches = 0;
matches = arr2.includes(result.quarterback) ? 1 : 0;
matches = arr2.includes(criteria2) ? 1 : 0;
matches = arr2.includes(criteria3) ? 1 : 0;
return matches >= X; // you can set the level of criteria that need to be matched
}))
console.log(filter2)
The main advantages of this solution over unmitigated's solution are
- Efficiency: You don't have to create temporary arrays that are going to be refiltered
- Flexibility: You can do a filter to match 2 of 3 criterias