0
\$\begingroup\$

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' 
 }
]
asked Dec 4, 2020 at 23:50
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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.

answered Dec 6, 2020 at 12:23
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.