How do I find part of an element within an array? (Javascript)

Asked

Viewed 47 times

0

I’m making a filter inside an array to pick up part of the element as typed in my search where:

array.filter(row => row.cnpj.indexOf(search) >= 0)

Considering 'search' the search typed, if inside the array, cnpj with null value will give error in the index:

TypeError: Cannot read property 'indexOf' of null

How do I filter this by ignoring the null values or else there is a better way to do this?

  • 1

    Could you show the rest of the code to understand the problem more easily?

1 answer

0

I found the answer:

value.filter(row => { 
   const cnpj = row.cnpj || ''
   return cnpj.indexOf(this.search) >= 0
})

Just put the expected value of the index in a const

  • Maybe it’ll help you use the method includes instead of indexof.

Browser other questions tagged

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