Search code examples
javascriptarraysinclude

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

Solution

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