0

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.

2
  • 1
    Can you post the array? Commented Sep 11, 2019 at 19:31
  • If I add const countries = [{name: 'USA'}, {name: 'Canada'}]; let filter = 'Canada'; before your code, countriesToShow contains [{name:'Canada'}] once it runs. Commented Sep 11, 2019 at 19:49

1 Answer 1

1

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'))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.