For example, let's say our application has role-based permissions that get populated as an array. That array might look like this:const roles = ['employee', 'manager']; We protect something in our app by applying restrictions to it, maybe like this:const restrictions = ['president', 'accountant']; What we need to know is does the user have the right role to lift the restriction. In other words, we want to know if the two arrays intersect.
Since there is no Array.intersect (yet) we have to come up with something. This is just what I use when I have two simple arrays (in this case two arrays of string values). We could add it to the Array prototype if we want, but I'm not going to show that here.
const roles = ['employee', 'manager'];
const restrictions = ['president', 'accountant'];
const matches = roles.filter(r => restrictions.includes(r));
Once this runs, matches contains all of the values that were in both arrays (so it's an empty array in this case). We can do evaluations on it like:
if (!!matches && !!matches.length) {
// do some stuff
}
BONUS: We can do the same thing with complex objects by applying the map function to this process. So if our array of roles looked like this:const roles = [{name: 'employee'}, {name: 'manager'}]; we could do the intersect like this:const matches = roles.map(r => r.name).filter(role => restrictions.includes(role));
I got this one and a couple of other goodies from this post on Medium. Happy coding!