Diego
Diego

Reputation: 268

Filter an array with another array INCLUSIVELY

I am having a hard time filtering an array by matching with all elements of another array, INCLUSIVELY. So for example:

var s = [
 {id: 1, area: ['foo', 'bar', 'other', 'again']},
 {id: 2, area: ['bar']},
 {id: 3, area: ['other']},
 {id: 4, area: ['foo']}
]

var areas = ['foo', 'bar']

Expected output should be:

[
 {id: 1, area: ['foo', 'bar', 'other', 'again']}
]

that is, each element in the expected result must contain ALL elements in the 'areas' array. This is what i tried but its returning an empty array so I think my function is wrong:

const filteredArray = s.filter(n => n.area.every(a => areas.includes(a)));

Upvotes: 0

Views: 48

Answers (1)

Nikita Madeev
Nikita Madeev

Reputation: 4380

You need to check that each element from areas is present in area field. In your example, you are doing the opposite, trying to check that each area field is present in areas.

const s = [
    { id: 1, area: ['foo', 'bar', 'other', 'again'] },
    { id: 2, area: ['bar'] },
    { id: 3, area: ['other'] },
    { id: 4, area: ['foo'] },
];
const areas = ['foo', 'bar'];

const result = s.filter(n => areas.every(a => n.area.includes(a)));

console.log(result);

Upvotes: 4

Related Questions