I am trying to filter the list by offerings
const questions = [
{ "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
{ "id": 1505, "offerings": [{"code": "AA"},{"code": "ABC"}]},
{ "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
];
const filterByArray = ['AB', 'DC'];
My expected outcome is to get back all the array elements based on what's passed in filterByArray
[
{ "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
{ "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
]
I tried filtering the array using
var filtered = questions.filter(function(element) {
return element.offerings.filter(function(cd) {
return filterByArray.indexOf(cd.code) > -1;
}).length === filterByArray.length;
});
console.log(filtered)
But this keep returning all array elements.
Use Array.some() and Array.includes().
const questions = [
{ "id": 2616, "offerings": [{"code": "AA"},{"code": "AB"}]},
{ "id": 1505, "offerings": [{"code": "AA"},{"code": "ABC"}]},
{ "id": 1500, "offerings": [{"code": "AC"},{"code": "DC"}]}
];
const filterByArray = ['AB', 'DC'];
const output = questions.filter(q => q.offerings.some(o => filterByArray.includes(o.code)));
console.log(output);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments