Javascript 检查两个数组中是否存在值 return 缺失值

Javascript check if value exsist in two arrays return missing value

我想知道如果某个值缺失,哪个值缺失。

Array1:你现在有这些值

['cloud:user', 'cloud:admin']

Array2:您需要拥有这些值才能继续

['cloud:user', 'cloud:admin', 'organization:user']

当前方法return是真还是假。但我想知道如果缺少一个值,则缺少哪个值。例如:'organization:user'。如果什么都不缺 return true.

let authorized = roles.every(role => currentResourcesResult.value.includes(role));

Just use filter method and check whether some of elements of arr1 is not equal to an element of an arr2:

const missingValues = arr2.filter(f => !arr1.some(s => s ==f));

一个例子:

let arr1 = ['cloud:user', 'cloud:admin']
let arr2 = ['cloud:user', 'cloud:admin', 'organization:user'];
const missingValues = arr2.filter(f => !arr1.some(s => s ==f));
console.log(missingValues);

您可以使用Array.prototye.filter()查看。

const domain = ['cloud:user', 'cloud:admin', 'organization:user'];
const data = ['cloud:user', 'cloud:admin'];

const notInDomain = domain.filter(item => data.indexOf(item) === -1);

if (notInDomain.length > 0) {
  console.log('Some values are not in the domain set');
}

console.log(notInDomain);

更新

您可以使用 includes 而不是 indexOf 获得相同的结果。

const notInDomain = domain.filter(item => !data.includes(item));