Repeat structure that compares equal values and prints the match

Asked

Viewed 144 times

-3

I have two arrays:

operator.table_perm has screen ids and the array canvases has in addition to the id, the name of the screens.

I need to create a repeat structure that compares the two arrays and printe the screen name.

I tried something like:

My array operator.table_perm:

(4) [1, 3, 9, 5]
0: 1
1: 3
2: 9
3: 5
length: 4

My array canvases:

0: {id: 1, nome_tela: "Cadastrar Operador", created_at: null}
1: {id: 2, nome_tela: "Tipo do Produto", created_at: null}
2: {id: 3, nome_tela: "Produtos", created_at: null}
3: {id: 4, nome_tela: "Custos Fixos", created_at: null}
4: {id: 5, nome_tela: "Custos Variáveis", created_at: null}
5: {id: 6, nome_tela: "Custos Extras", created_at: null}
6: {id: 7, nome_tela: "Listagem dos Custos Fixos", created_at: null}

The operator.tabela_perm array has the IDS values of the screens. The screen array has id and name, I need to print the name of the screens that exist in the table_perm.

    for(let i=0; i<this.operador.tabela_perm.length; i++){
      for(let j=0;j<this.operador.tabela_perm.length; j++){
        if(this.operador.tabela_perm[i] == this.telas[j].id){
          console.log(this.telas[j].nome_tela)
        }
      }
    }
  }
  • It needs bigger context. For me everything is ok.

  • This way some names are not printed, even when the two arrays have the same ID

  • Needs a Complete and verifiable minimum example so that it is easy to see the problem and present a solution

  • I made an edit in the publication

  • According to the example of input data you gave, what output would you expect to see ?

  • Register Operator, Products, Variable costs

Show 1 more comment

2 answers

1


What’s happening is that in your second for, the stopping condition is this.operador.tabela_perm.length, that in the I example is 4, then its if will only compare until position 4 of the array of screens, your code should be like this:

for(let i = 0; i < this.operador.tabela_perm.length; i++) {
    for(let j = 0; j < this.telas.length; j++) {
        if(this.operador.tabela_perm[i] == this.telas[j].id) {
            console.log(this.telas[j].nome_tela)
        }
    }
}

0

As you are using Typescript, it would be nice for you to use its features, such as Arrow Functions, follows an example of what the same solution above would look like.

tabela_perm.forEach((perm)=>{
  console.log(telas.find((telaName)=> telaName.id == perm).nome_tela)
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.