Filter with Typescript

Asked

Viewed 376 times

0

I have the following code :

search(evento){
this.str = evento.target.value;
console.log('str ',this.str)

this.cartoes.forEach(element => {
if(element.codigo.search(this.str) !== -1 && this.cartoesFiltro.length === 0){
  this.cartoesFiltro.push({
    idtag: element.idtag,  
    codigo: element.codigo,
    alocada: element.alocada,
    nome: element.nome
  })      
  console.log('cartoesFiltro ',this.cartoesFiltro);      

  //this.idProcura = element.idtag;
  //console.log('aqui',this.idProcura);      
}
if(element.codigo.search(this.str) !== -1 && this.cartoesFiltro.length !== 0 ){
  this.cartoesFiltro.forEach(dado => {
    if (dado.idtag === element.idtag){
      console.log('existe')
    }
    else{
      this.cartoesFiltro.push({
        idtag: element.idtag,  
        codigo: element.codigo,
        alocada: element.alocada,
        nome: element.nome
      })
    }
  });
   //this.cartoesFiltro = [];
   //console.log('aqui ',this.cartoesFiltro)
}
if(element.codigo.search(this.str) === -1 && this.cartoesFiltro === 0){
  console.log('nachou');
  this.cartoesFiltro = [];
}
if (this.str === ''){
  console.log('ndeu');
  this.cartoesFiltro = [];
  console.log('cartoesFiltro ',this.cartoesFiltro);

}
}

Theoretically it should search something in an array, and find itself inserted in a second array. But he’s inserting the same thing more than once, how can I fix it ?

2 answers

0

Divide this into "Trials":
- First, find the elements that have the code you want
- Second, when iterating under the found ones
filtered, then send it to a new array
- at the end shows the result of the array with the filtered items.

search(evento) {
  if (!evento || !evento.target || !evento.target.value) return;
  this.str = evento.target.value;

  // primeiro, procura-se os codigos
  const comCodigo = this.cartoes.filter(ele => ele.codigo.includes(this.str));

  // depois iteramos sob os achados, e se ele não for encontrado dentro dos filtrados, faz push para lá
  comCodigo.forEach(ele => {
    if (!this.cartoesFiltro.find(_ele => _ele.idtag === ele.idtag)) 
      this.cartoesFiltrados.push(ele)
  })

  // por fim, retorna o que foi encontrado
  return this.cartoesFiltro;
}

repl.it Session

0

Good morning,

To solve your problem I believe it could be done as follows:

this.cartoesFiltro = this.cartoes; // apenas para manter o original sem 

this.cartoesFiltro  =this.cartoesFiltro.filter(x=>x.idtag.indexOf(element.idtag)); // Aqui vai pegar todos que contem esse filto

If you want a real-time search, in HTML use [(ngModel)] = "filtro" and make this method in the variable SET.

I believe this will solve your problem.

Browser other questions tagged

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