Abhishek Dasgupta
Abhishek Dasgupta

Reputation: 618

filtered array outputs an empty array . How to fix it?

I am new to react-native and javascript. I am trying to filter an array of objects, where each object represents a country and has a member variable called name. I have created the following search filter to save countries with search keyword.

I have console.logged every step in between the following function, from array of country's state to filter's state and even the condition includes() also returns true.

const App = () => {
  const [countries,setCountries] = useState([])
  const [filter,setFilter] = useState('')

  useEffect(() =>{
    axios.get('https://restcountries.eu/rest/v2/all')
    .then(response => setCountries(response.data))
  }, [])

  //console.log('countries[] = ',countries)

  const rows = () => {
    const len = countriesToShow.length 
    if(len > 10){
      return(<p>Too many matches, specify another filter</p>)
    }
    else if(len >=1 && len <= 10){
      return(countriesToShow.map(country => <p>{country.name}</p>))
    }

  }


  const handleFilterChange = (event) => {
    setFilter(event.target.value)
  }

const countriesToShow = filter === '' ? [] : countries.filter(country => country.name.toLowerCase().includes(filter.toLowerCase()))

 return(
    <div>
      find countries
      <input value={filter} onChange={handleFilterChange} />
      {rows()}
    </div>
  )
}

export default App;

I expect an array with the filtered country names but I am actually getting an empty array.

Upvotes: 0

Views: 69

Answers (1)

Rohit Kashyap
Rohit Kashyap

Reputation: 1592

Try this:

This is a reusable function which you can use to filter an array using a key of your choice, this can further be made reusable by passing in a custom attribute.

var arr = [
  {
    id: 1,
    country: 'IN'
  },
    {
    id: 2,
    country: 'US'
  },
    {
    id: 3,
    country: 'CH'
  },
    {
    id: 4,
    country: 'UK'
  }
]

const fn = (data, key) => ( data.filter(d => ( d.country.toLowerCase().indexOf(key.toLowerCase()) > -1 )))

console.log(fn(arr, 'IN'))

Upvotes: 1

Related Questions