Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Andy Hartono
Full Stack JavaScript Techdegree Student 12,335 PointsPlease let me know what's wrong with the code I wrote
const phoneNumbers = ["(503) 123-4567", "(646) 123-4567", "(503) 987-6543", "(503) 234-5678", "(212) 123-4567", "(416) 123-4567"];
let numberOf503
// numberOf503 should be: 3
// Write your code below
const regex = /\(?503.*/gm
numberOf503 = phoneNumbers.reduce((count, phone) => {
if(regex.test(phone)) {
return count += 1
}
else {
return count
}
}, 0)
console.log(numberOf503);
This is my answer to the challenge. I really don't understand why the console.log is printing 2 instead of 3. Somehow, the last 503 is not being captured ("(503) 234-5678")
const phoneNumbers = ["(503) 123-4567", "(646) 123-4567", "(503) 987-6543", "(503) 234-5678", "(212) 123-4567", "(416) 123-4567"];
let numberOf503;
// numberOf503 should be: 3
// Write your code below
2 Answers

Cody Hansen
5,516 PointsWhen using test() on a RegExp with the global(g) flag, it tracks the lastIndex and starts from there instead of 0. Since you have two 503 numbers back to back, it is missing the second and not counting it! If you remove the g from your regular expression, the code works perfectly!
I'm not great at explaining and had to do some digging myself to even word this answer... However, this stack overflow question goes into better depth than I can!: https://stackoverflow.com/questions/1520800/why-does-a-regexp-with-global-flag-give-wrong-results
I hope this helps!

Andy Hartono
Full Stack JavaScript Techdegree Student 12,335 PointsAhh, thank you very much Cody. I got it now