Skip to content
Advertisement

How can I filter through an array an return it instead of another one in this Svelte project?

I am working on a small Svelte application, for learning purposes (Im new to Svelte).

The application displays a JSON of countries in a Bootstrap 4 table. There is also a text box that can be used to filter through the countries:

const apiURL = "https://gist.githubusercontent.com/Goles/3196253/raw/9ca4e7e62ea5ad935bb3580dc0a07d9df033b451/CountryCodes.json";

let countries = [];
let filteredCountries = [];
let stringToMatch = '';

onMount(async function() {
    const response = await fetch(apiURL);
    countries = await response.json();
    filteredCountries = countries;
});

function filterList(){
  filteredCountries = countries;

  if(stringToMatch){
    filteredCountries = countries.filter(country => {
        return country.name.toLowerCase().includes(stringToMatch.toLowerCase()) || country.code.includes(stringToMatch.toUpperCase());
    });
  }
}

See a REPL with the entire code HERE.

I am looking for a way to filter through the countries array and return it filtered, instead of using JavaScript’s filter() method which requires storing the results in another variable.

In other words, I wish I would not need the filteredCountries variable.

Is that possible? How?

Advertisement

Answer

An idea would be to use an getFilteredCountries() function so you don’t need this filteredCountries variable.

You can define it like that:

function getFilteredCountries(countries, stringToMatch){
    if(stringToMatch){
        return countries.filter(country => {
            return country.name.toLowerCase().includes(stringToMatch.toLowerCase()) || country.code.includes(stringToMatch.toUpperCase());
        });
    } else {
        return countries
    }
}

and consume it in your #each:

{#each getFilteredCountries(countries, stringToMatch) as country}   
    <tr>
        <td>{country.name}</td>
        <td class="text-right">{country.code}</td>
    </tr>
{/each}

See a REPL with the entire code HERE.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement