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 trial

JavaScript JavaScript Array Iteration Methods Array Manipulation Practice reduce()

Help refactoring long Array.reduce() call

Hello all,

The only way I could make the following reduce() call work feels long-winded and I wonder how one could refactor the code so it looks cleaner. Any help much appreciated.

numberOf503 = phoneNumbers.reduce((count, phone) => {
  if (phone.slice(1,4) === '503') {
    return count + 1;
  } else {
    return count;
  }
}, 0);

Best, J.

1 Answer

Greg Kaleka
Greg Kaleka
39,021 Points

Looks pretty good to me. Very readable and understandable. Don't get too caught up in wanting your code to look "elegant". The most important thing is that you can quickly understand what's happening in your code.

The only thing you could do to make this a bit shorter if you wanted would be to eliminate the else clause. Let me know if you don't see why we can do this.

numberOf503 = phoneNumbers.reduce((count, phone) => {
  if (phone.slice(1,4) === '503') {
    return count + 1;
  }
  return count;
}, 0);

Cheers :beers:

-Greg

Thanks a lot for your input!