There are two arrays containing the values. You need to compare whether it contains another array at least one value from the other array and return true or false.

Is there any other more elegant method without iteration, create proishodachego array and two checks?

Is there any other more elegant method without iteration, create proishodachego array and two checks?

```
const userRoles = ['user', 'admin']
const allowedRoles = ['John', 'admin']
function roles (roles...) {
let allowed = roles.map(role => {
return userRoles.includes(role)
})
if (allowed.includes(true)) {
//
} else {
//
}
}
roles(allowedRoles)
```

asked March 12th 20 at 08:01

2 answers

answered on

Solution

`allowedRoles.some(n => userRoles.includes(n))`

answered on March 12th 20 at 08:05

Either compare each element of the first array with each element of the second array.

Or you can sort both arrays and compare as follows:

if a[i] .lt. b[j] then

i++

else if a[i] .gt. b[j] then

j++

else they are equal - so we found what you need

Or you can sort both arrays and compare as follows:

if a[i] .lt. b[j] then

i++

else if a[i] .gt. b[j] then

j++

else they are equal - so we found what you need

Horror) commented on March 12th 20 at 08:08

@beulah38, what are You so scared? Well, the language is a bit unconventional, abstract. Well, the program is not entirely written and only the internal structure of the cycle, and no boundary conditions (initialization of the indexes, the exit condition). I have just the basic meaning outlined. commented on March 12th 20 at 08:11

Find more questions by tags JavaScript

Read what is the complexity of the algorithms.

In short, if You have an array and You need to check for a match element in another array, those methods in the worst case we need to compare each element of each, it turns out that if the length of the array N and the second array M, then we have N*M operations if the arrays are comparable in size, that have complexity N2. But if the sizes of the arrays are large, it takes a long time.

Simple conclusion, if You see the cycle of large collections - think about it, if a nested loop - think twice. Of course, when this is justified or when the number of elements is small then no need to worry, but if more and cycles...

On account of this decision - it is beautiful and correct, but just need to understand what is behind it. - Hilario60 commented on March 12th 20 at 08:15