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 Iteration Examples Using forEach()

Andrew Phythian
Andrew Phythian
19,747 Points

Alternative Solution

Posting a different solution method to the video (and others already posted). I index the location of the first instance of the letter S in each name in the array and if it was 0 (the first letter), I added the name to the array.

const names = ['Selma', 'Ted', 'Mike', 'Sam', 'Sharon', 'Marvin'];
var sNames = [];

names.forEach(name => {
  if(name.indexOf("S") == 0) {

Returns the following in the console...

[ 'Selma', 'Sam', 'Sharon' ]  
Teacher Russell
Teacher Russell
16,872 Points

https://w.trhou.se/2pvtky460u and yet another way........This was the first thing that popped into my head when I paused the video.

1 Answer

16,701 Points

Looks good.

I tried to fit it all onto one line and came up with this.

names.forEach( name => (name[0] === 'S') ? s.push(name) : 0);

you can make it even shorter, but its pretty unreadable