# Improving a filter array function with Set and objects, to match elements and conditions

I've posted a similar question on: Link

With the help of the other users, I was able to improve the code, but I don't think is the "ultimate" form.

Thats my code now, any help?

Conditions entries example:

[1,2],
[9,6,4],
[3]
[7,1,5,2,3]

private filterElements(userSelectedConditions: Set<number>): Element[]{
const meetConditions: Element[] = [];

this.arrayWithAllElements.forEach(element => {

let isPossibility: boolean = true;

for (let ev of userSelectedConditions ) {
if( !element.condition_matrix.includes( ev ) ){
isPossibility = false;
break;
}
}

if(isPossibility){
meetConditions.push(element);
}
});

if(meetConditions.length === 0){
meetConditions.push( { <a_filler_object> } );
}

return meetConditions;
}


The user select some conditions, and this code has to iterate on the full elements list, filter the elements that meets all the conditions passes. So if the user selects ONE condition, every element with that condition should be filtered. IF the user selects THREE conditions, every element that meet those conditions should be filtered, if they don't match ALL the selected conditions, they should be out of the list.

this.selectedConditions is already maped by ID

Elements list example:

elements: [
{
name: 'el1',
condition_matrix: [1,2]
},
{
name: 'el2',
condition_matrix: [2,3]
},
{
name: 'el3',
condition_matrix: [2,1]
}
]


Conditions list example:

conditions: [
{
id: 1
name: 'cond1'
},
{
id: 2
name: 'cond2'
},
{
id: 3
name: 'cond3'
}
]


The Array methods filter() and every() come in very handy here. First you could define a function to check wheter a given element matches all conditions:

function meetsAll(element, conditions) {
return conditions.every(c => element.condition_matrix.includes(c));
}


Now it's almost trivial to filter out the matching elements using Array.filter():

const meetConditions = this.arrayWithAllElements.filter(
element => meetsAll(element, userSelectedConditions)
);


I recommend you also have a look at the other functional methods defined on Array.