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 trialBrendan Dzeguze
Front End Web Development Techdegree Graduate 14,567 Pointsmy code isnt working.
i am getting the message "looks like you haven't changed the value of numberOf503 yet." i thought that i did! what's going on?
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
function myFunc(total, num){
if (num.substring(1, 5) == "(503)"){
return total + 1;
}
}
numberOf503 = phoneNumbers.reduce(myFunc);
1 Answer
Rob Bridges
Full Stack JavaScript Techdegree Graduate 35,467 PointsHey I know you asked this like a month ago but I just did this challenge and came across your code, there are two main problems, you aren't passing a default value to initiate total at, so the reduce function just pulls the first value from the array by default, we can set the total value to zero by passing a second parameter to the reduce function as seen below.
Also your sub string starts count at index 1, which is actually the second value in the string since sub string treats the string as a Character array it is zero based.
Also make sure your function is still returning total even if the conditions aren't met, otherwise it's not going get the correct count;
I copied below a few quick changes to make your code work below.
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
function myFunc(total, num){
if (num.substring(0, 5) == "(503)"){ //changing the substring value to check at the first index
return total + 1;
}
return total; // returning the total to still keep an accurate count even if the if condition is not incrementing
}
numberOf503 = phoneNumbers.reduce(myFunc,0); //setting total to a 0 so that it doesn't try to set the answer to the first array element