Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looping through array of booleans to determine which object to include in another array

I have a Javascript question related to mapping. So I have two arrays…

Array1

[
    {
        "id": 1,
        "name": "admin"
    },
    {
        "id": 2,
        "name": "analyst"
    },
    {
        "id": 3,
        "name": "reviewer"
    },
    {
        "id": 4,
        "name": "administrator"
    },
    {
        "id": 5,
        "name": "leader"
    }
]

Array2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[ false, false, false, false, false]

I want to create a third array. So I create a variable and set its initial value to be empty.

const roles = [];

What I want to do is include the objects in Array1 into roles based on the boolean values in Array2 in sequential order.

For example, if Array2 looks like [true, false, true, false, false], then roles would be this…

roles = [
{
        "id": 1,
        "name": "admin"
    },
    {
        "id": 3,
        "name": "reviewer"
    },
]

The reason is because the first and third boolean values in Array2 are true, therefore it takes the first and third objects in Array1 and puts them into roles

I know that either .map or .forEach is the solution here, but I don’t quite know the best approach.

Can anyone assist?

Thanks!

>Solution :

You can filter array one and return value based on array 2 to filter out data like below :-

const roles = array1.filter((item, index) => array2[index]);

Answer to 2nd query from comment, if you just want to return id :-

const roles = array1.filter((item, index) => array2[index]).map((filtered) => ({id: filtered.id}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading