JavaScript JavaScript Array Iteration Methods Array Manipulation Practice reduce()

Daniel Jacoshenk
Daniel Jacoshenk
5,542 Points

Can someone help find the error in my code? Bummer: Looks like you haven't changed the value of `numberOf503` yet.

Can't seem to figure out what I'm doing wrong with the reduce method. I keep getting the following error.

Bummer: Looks like you haven't changed the value of numberOf503 yet.

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

numberOf503 = phoneNumbers.reduce((count, number) => {
  if (number.substring(0, 5) === '(503)') {
    return count + 1;
  } else {
    return;
  }
}, 0);

console.log(numberOf503);

2 Answers

Eduard Edwin
Eduard Edwin
14,562 Points

Hi Daniel. Instead of returning the count from inside the if statement, try returning it outside of the if statement. Delete the else block altogether.

You can also write count + 1 as count++. The code looks concise that way while still maintaining the correct behaviour.

Hi,

Your code is good, you just need to return the count like this.

else { return count; }

and this is another approach if you would like to make your code short

numberOf503 = phoneNumbers.reduce((c, n) => (n[1] === '5' ? c+1 : c), 0)

Or

numberOf503 = phoneNumbers.reduce((c, n) => (n.slice(0, 5) === '(503)' ? c + 1 : c), 0)