H-Dev
H-Dev

Reputation: 13

Compare array with another array, matching all elements (TypeScript, Angular Pipe)

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.

Upvotes: 1

Views: 2060

Answers (1)

Julien Maret
Julien Maret

Reputation: 589

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)));

Upvotes: 2

Related Questions