Home > database >  Function to search array and return array of elements with specified similarities
Function to search array and return array of elements with specified similarities

Time:06-05

Beginning coder here taking a course in js. I'm stuck on a problem asking me to write a function that takes an array of different countries and returns arrays of countries that have specified commonalities (eg: return countries that end in 'land' or 'ia' as an array). Here's the code I have written:

const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland', 'Ethiopia']
    function categorizeCountries(keyword) {
        for (country of countries) {
            if (keyword = 'land') {
                console.log([countries.filter((country) => country.endsWith('land'))])
            } else if (keyword = 'en') {
                console.log([countries.filter((country) => country.endsWith('ia'))])
            } else if (keyword ='ia') {
                console.log([countries.filter((country) => country.endsWith('en'))])
            } else {
                console.log('Country does not Exists')
            }
        } 
    }
    console.log(categorizeCountries(['land']))
    console.log(categorizeCountries(['en']))
    console.log(categorizeCountries(['ia']))

The console only returns the arrays that meet the 'land' specification, and returns the same array 5 times for each search. I've tried multiple things and this is what's got me the closest, I just don't know what I'm missing. Any help is welcome.

CodePudding user response:

.filter is already looping through the array; same as a for-loop. Using the param keyword on .endsWith would suffice

function categorizeCountries(keyword) {
  return countries.filter((country) => country.endsWith(keyword));
}

CodePudding user response:

you are doing a lot of things wrong, but nice try nonetheless.

  1. filter already filters through an array you don't need to use the for loop.
  2. passing array to categorizeCountries(['in']) is useless, try calling it with just a string categorizeCountries('in')
  3. try to implement this with a switch case statement, since it's better use case than if statement
  4. console.log() returns void that is why in the end it's printing undefined.

const countries = ['Finland', 'Sweden', 'Denmark', 'Norway', 'Iceland', 'Ethiopia']
function categorizeCountries(keyword) {

    if (keyword == 'land') {
        console.log(countries.filter((country) => country.endsWith('land')))
    } else if (keyword == 'en') {
        console.log(countries.filter((country) => country.endsWith('ia')))
    } else if (keyword =='ia') {
        console.log(countries.filter((country) => country.endsWith('en')))
    } else {
        console.log('Country does not Exists')
    }

}
categorizeCountries('land')
categorizeCountries('en')
categorizeCountries('ia')

result should be:

['Finland', 'Iceland']
['Ethiopia']
['Sweden']
  • Related