Angular search array

Asked

Viewed 43 times

0

I’m having a problem fetching data from an array

buscarDados(cep: string, uf: string, cidade: string): CEP[] {
    this.storedNames = JSON.parse(localStorage.getItem("enderecos"));
    return this.storedNames.filter((endereco: CEP) => 
        endereco.cep.indexOf(cep) !== -1 ||
        endereco.uf.indexOf(uf) !== -1 ||
        endereco.cidade.indexOf(cidade) !== -1);
  }

When I inform for example a zip code that exists in the array with an invalid city or UF and the query is made. Which can’t be right. For example if you type 11111-111, Campinas and SP in an array that only has 11111-111 and SP valid the search is done. You should not let this search because SP does not exist in the array.

What’s wrong with my search method?

  • 1

    If you need the three conditions to be met, you need to use && instead of ||.

1 answer

0

Try this:

  buscarDados(cep: string, uf: string, cidade: string): CEP[] {
    this.storedNames = JSON.parse(localStorage.getItem("enderecos"));
    return this.storedNames.filter((endereco: CEP) => 
        endereco.cep.includes(cep) &&
        endereco.uf.includes(uf) &&
        endereco.cidade.includes(cidade));
  }
  • I tried this way only that in the case search for all the entered fields. In case I need to inform one or more valid fields to do the search

Browser other questions tagged

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