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.

JavaScript JavaScript Array Iteration Methods Array Manipulation Practice reduce()

my 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?

app.js
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
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Rob Bridges
Full Stack JavaScript Techdegree Graduate 31,164 Points

Hey 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