R
R
riddlr2018-10-09 19:54:13
JavaScript
riddlr, 2018-10-09 19:54:13

Another way to compare 2 arrays and return true/false?

There are two arrays containing values. We need to compare whether another array contains at least one value from another array and return true or false.
Is there another more elegant way without iteration, creating an intermediate array and two checks?

const userRoles = ['user', 'admin']
const allowedRoles = ['vasya', 'admin']

function roles(...roles) {
    let allowed = roles.map(role => {
      return userRoles.includes(role)
    })
    if (allowed.includes(true)) {
      //
    } else {
      //
    }
}

roles(allowedRoles)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-10-09
@riddlr

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

K
Karpion, 2018-10-09
@Karpion

Or compare each element of the first array with each element of the second array.
Or sort both arrays and compare like this:
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 we need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question