The M
The M

Reputation: 661

Javascript check if value exsist in two arrays return missing value

I'd like to know IF a value is missing which one is missing.

Array1: You have these values at the moment

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

Array2: You need to have these values in order to continue

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

Current method which returns true or false. But I'd like to know IF a value is missing which one is missing. For example: 'organization:user'. If nothing is missing return true.

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

Upvotes: 0

Views: 29

Answers (2)

StepUp
StepUp

Reputation: 38134

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));

An example:

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);

Upvotes: 1

Sajeeb Ahamed
Sajeeb Ahamed

Reputation: 6390

You can check it by using 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);

Update

You can gain the same result by using includes instead of indexOf.

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

Upvotes: 0

Related Questions