0

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

1 Answer 1

4

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

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

2 Comments

thanks very much. That works for that array. but i just realized my array was slightly differently structured... The array area in s should actually be an array of objects like this: s = [ { id: 1, area: [{area: 'foo'}, {area: 'bar}', {area: 'other}', {area: 'again'}] }, { id: 2, area: [{area: 'bar}'] }, { id: 3, area: [{area: 'other'}] }, { id: 4, area: [{area: 'foo'}] }, ]; how would the function be in this case?
@Diego Try it s.filter(obj => areas.every(filterArea => obj.area.map(areaObj => areaObj.area).includes(filterArea)));

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.