Skip to content
Advertisement

Find how many times a char is included into an array of names

I’m trying to do the following exercise in JavaScript: I need to return the number of times the letter ‘l’ is used inside an array of names.

This is an example of the array I have to use:

["earth (c-137)","abadango","citadel of ricks","worldender's lair","anatomy park","interdimensional cable","immortality field resort","post-apocalyptic earth","purge planet","venzenulon 7","bepis 9","cronenberg earth","nuptia 4","giant's town","bird world","st. gloopy noops hospital","earth (5-126)","mr. goldenfold's dream","gromflom prime","earth (replacement dimension)","testicle monster dimension","signus 5 expanse","earth (c-500a)","rick's battery microverse","the menagerie","earth (k-83)","hideout planet","unity's planet","dorian 5","earth (unknown dimension)","earth (j19ΞΆ7)","roy: a life well lived","eric stoltz mask earth","earth (evil rick's target dimension)","planet squanch","glaagablaaga","resort planet","interdimensional customs","galactic federation prison","gazorpazorp"]

Note that the letter ‘l’ might be repeted inside a single name.

Is there any JS method I could use to do this ? I’ve tried with indexOf but couldn’t make it work

Advertisement

Answer

Try this:

myStr.split('<my_char>').length - 1. 

This splits the string everytime you see the char you want and returns the number of strings after splitting at the delimiter minus 1 which is exactly what you want. Do this after converting the array of strings to a single string. myStr = myStrArray.toString();

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