1

I have been wrapping my head around a filtering issue I have in an Angular Pipe.

A multiselect component contains a string array of elements, of which the selection acts as an AND operation. What I want to do is return all items matching at least all the items in the filter.

I have so far used some for this, which works great for OR, so I thought that every would do the same for AND, but in the parent filter it always returns all the items, meaning the condition is always true.

This is a simplified extract of my code

let filterItems: string[] = ['1', '2', '3', '4', '5', '6'];
let filterSelection: string[] = ['2', '3'];
let item1: string[] = [];
let item2: string[] = ['2'];
let item3: string[] = ['2', '3'];
let item4: string[] = ['2', '3', '5', '6'];

console.log(item1.every(x => filterSelection.includes(x)));
console.log(item2.every(x => filterSelection.includes(x)));
console.log(item3.every(x => filterSelection.includes(x)));
console.log(item3.every(x => filterSelection.includes(x)));

The expected result would be

Item1: false

Item2: false

Item3: true

Item4: true

Only when the AND conditions are met, the item should be returned. I am probably misinterepreting the use of every here, but have tried several things, such as switching the arrays around, using indexOf instead of includes, using some, negated some with filter, but none of them give the result I want.

1 Answer 1

2

You swaped your arrays for what you want.

let filterItems: string[] = ['1', '2', '3', '4', '5', '6'];
let filterSelection: string[] = ['2', '3'];
let item1: string[] = [];
let item2: string[] = ['2'];
let item3: string[] = ['2', '3'];
let item4: string[] = ['2', '3', '5', '6'];

console.log(filterSelection.every(x => item1.includes(x)));
console.log(filterSelection.every(x => item2.includes(x)));
console.log(filterSelection.every(x => item3.includes(x)));
console.log(filterSelection.every(x => item4.includes(x)));

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, must have overlooked this since the original code is a lot more complex than what is shown here. AND filter is working as expected now.
I advice you to create a small function for this kind of thing so you can test if the function work with simple knowed value (like here) before insert it in your code

Your Answer

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.