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 Return a Single Value from an Array with reduce()

Peter Retvari
seal-mask
.a{fill-rule:evenodd;}techdegree
Peter Retvari
Full Stack JavaScript Techdegree Student 8,392 Points

I think you don't have to use if to solve the "Starts with G" challenge

Hi Guys,

Could you please check my code? It returns 4 and I think it's more simple:

const names = ['Gary', 'Pasan', 'Gabe', 'Treasure', 'Gengis', 'Gladys', 'Tony'];

    // Result: 4

const startsWithG = names.reduce(

  (names, name) => names + (name[0] === 'G'),

  0
);

console.log(startsWithG);

in the parenthesis you should write your statement. If it's true, the name will added to the names acc.

1 Answer

Steven Parker
Steven Parker
210,143 Points

That's very clever! But while relying on type coercion to convert a boolean into a number works, it is a bit obscure.

I'd probably write it like this:

  (names, name) => names + (name.startsWith('G') ? 1 : 0),
Steven Parker
Steven Parker
210,143 Points

That's the ternary operator. If the first term evaluates to "true", then it returns the second one. Otherwise, it returns the third one. So I'm explicitly converting the boolean value (either from a comparison or the "startsWith" method) into a numeric value of 1 or 0.

For more details, see the MDN page.