0

I want to be able to filter a list of users by a list of roles a user may have.

A demonstration of the behaviour I am trying to create. This code creates the results I am expecting but obviously isn't very practical when dealing with an undetermined number of selected filters.

const users = result.data.filter(({roles}) => { switch (selections.length) { case 1: return roles.find((role) => role.id === filter[0]); case 2: return ( roles.find(({id}) => id === filter[0]) && roles.find(({id}) => id === filter[1]) ); case 3: return ( roles.find(({id}) => id === filter[0]) && roles.find(({id}) => id === filter[1]) && roles.find(({id}) => id === filter[2]) ); case 4: return ( roles.find(({id}) => id === filter[0]) && roles.find(({id}) => id === filter[1]) && roles.find(({id}) => id === filter[2]) && roles.find(({id}) => id === filter[4]) ); default: return true; //If there are no items in Select return all users. } }); 

Any help is appreciated.

Edit - restructured users, roles.

1 Answer 1

2

If the number of filters you need to search through is connected to the length of the selections, then you could use a simple loop to iterate each filter, like so:

const users = result.data.filter(({roles}) => { if (selections.length < 1) return true; for (let i = 0; i < selections.length; i++) { if (!roles.find(({id}) => id === filter[i])) { return false; } } return true; }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I just tested and this works perfectly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.