Skip to main content

Command Palette

Search for a command to run...

Counting the number of occurrences in a string using a higher-order function

Updated
1 min read
Counting the number of occurrences in a string using a higher-order function

I was recently working on some code that required me to count the number of occurrences of an @ in a string. Initially, I created the following:

const matches = (email.match("@")||[]).length;

However, the ||[] which defaults to an empty array if no @ characters are found strikes me as rather hard to read. Looking for alternatives, I found that you could use filter() instead:

const matches = [...email].filter(char => char === "@").length

I'm not convinced this is much clearer, but it's always good to see how other people tackle the same problem, you'll always learn new things.

More from this blog

Today I Learned

15 posts