Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAndy 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,517 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