Perform Same Operations with Different Values in the Filter Method

Asked

Viewed 22 times

0

Good afternoon. I have the following code:

const getCountries = async() => {
  const response = await fetch("https://coronavirus-19-api.herokuapp.com/countries");
  const datas = await response.json();

  const selectOnlyCountries = country => 
  country !== 'North America' && country !== 'Asia' && country !== 'South America';

  const countries = datas.filter(({ country }) => selectOnlyCountries(country));
}

getCountries();

He gets a array of a API with countries and continents, however, I only wanted countries.

With this, I arrived in a normal solution of use of filter, but I wish I didn’t have to keep repeating the country !== valor.

In such a way, I tried the following:

const getCountries = async() => {
  const response = await fetch("https://coronavirus-19-api.herokuapp.com/countries");
  const datas = await response.json();

  const excludePlaces = [
    'North America', 
    'South America', 
    'Asia'
  ]

  const countries = datas.filter(({ country }) => excludePlaces.some(place => place !== country))
}

getCountries();

It didn’t work. The variable countries continues with the same array of dates.

Does anyone have any solution to this problem?

From now on, thank you for your attention!

1 answer

0

Hello, you can replace the function some for includes. Some will test all the alternatives until finding a positive value, if the country compared is "North America" for example, it will return false when compared to himself within its logic, but true when compared to the next element, while includes will check whether the desired value exists within the array.

The comparison code would be this

datas.filter(({ country }) => !excludePlaces.includes(country))

More about the function some here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

  • In fact, you can keep the Some function if you change the location in the negative (!), the result would be this countries = datas.filter(({ country }) => !excludePlaces.some(place => place === country))

  • That’s what I wanted. I had no knowledge of this method includes for array, I thought it was only usable in string. Thank you so much for your help!

Browser other questions tagged

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