'Create a new array of boolean values by comparing two arrays with objects

I have a question about creating JavaScript arrays. Here's what I want to do.

I have two arrays. Each array has object(s) in them.

The first array has exactly 5 objects, each with a key/value pair (id/name). This array will ALWAYS have 5 objects.

Here's what it looks like...

[
    {
        "id": 1,
        "name": "AnalyticalAdmin"
    },
    {
        "id": 2,
        "name": "Analyst"
    },
    {
        "id": 4,
        "name": "AdminReviewer"
    },
    {
        "id": 5,
        "name": "SystemAdministrator"
    },
    {
        "id": 6,
        "name": "CaseworkSTRTechLeader"
    }
]

The second array will have either...

  1. no objects,

  2. 4 or less objects,

  3. exactly 5 objects.

In the example below, the second array only has one of the 5 objects in the first array...

[
    {
        "id": 4,
        "name": "AdminReviewer"
    }
]

I need to create a third array that has exactly 5 boolean values that are determined by comparing the first two arrays.

For example, based on the first two arrays above, the third array would be...

[false, false, true, false, false]

The reason the third array would look like this is because "AdminReviewer" is the third object in the first array, so the third boolean value in the third array would be true (since it's a match).

But because the first, second, fourth, and fifth objects in the first array do not exist in the second array, their boolean equivalent in the third array would be false.

To accomplish this, I know I need to either do a compare function on the first two arrays to create the third array (of booleans) or I need to run a for loop on the first array, comparing it to the second array to create the third array (of booleans).

Can anyone help me with this?



Solution 1:[1]

This could be done as follows:

const filterStrings = filterArray.map(o => JSON.stringify(o));
const result = baseArray.map(o => filterStrings.includes(JSON.stringify(o)));

Please take a look at below runnable code and see how it works.

const baseArray = [
    {
        "id": 1,
        "name": "AnalyticalAdmin"
    },
    {
        "id": 2,
        "name": "Analyst"
    },
    {
        "id": 4,
        "name": "AdminReviewer"
    },
    {
        "id": 5,
        "name": "SystemAdministrator"
    },
    {
        "id": 6,
        "name": "CaseworkSTRTechLeader"
    }
];

const filterArray = [
    {
        "id": 4,
        "name": "AdminReviewer"
    }
];

const filterStrings = filterArray.map(o => JSON.stringify(o));
const result = baseArray.map(o => filterStrings.includes(JSON.stringify(o)));
console.log(result);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 uminder