Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
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

[ 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?

UPDATE

I got this error

Element implicitly has an 'any' type because expression of type 'number' can't be used to index type 'FormArray'.
  No index signature with a parameter of type 'number' was found on type 'FormArray'.

const roles = this.listOfRoles.filter((item, index) => this.rolesArray[index]).map((filtered) => ({ id: filtered.id }));

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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}));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda