Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
Let's walkthrough the solution to the second code challenge.
-
0:00
For this challenge, we need to use the forEach method to copy
-
0:03
only the first 2 characters of each string in the days array.
-
0:07
And store the abbreviations in the dayAbbreviations array.
-
0:11
Like I did earlier, I'm going to copy and paste the code for
-
0:14
this challenge into the Atom text editor in order to make the code easier to read.
-
0:22
So the days array contains seven strings, one string for each day of the week.
-
0:28
And what we want to end up with is an abbreviation for each of those strings or
-
0:32
each of those days.
-
0:34
So Su for Sunday.
-
0:37
Mo for Monday and so on.
-
0:39
Let's look at my solution.
-
0:41
Again, I started by adding the call for each method.
-
0:45
And then, the anonymous call back function using arrow function syntax.
-
0:49
So, days.forEach.
-
0:54
And, I use day for the current value parameter name.
-
0:57
Day, and then a fat arrow.
-
1:00
Then I added a set of curly braces to define a code block.
-
1:04
Let's add a variable for the dayAbbreviation.
-
1:06
So const dayAbbreviation.
-
1:12
To get the first two characters of each day string, I used the slice method.
-
1:16
So day.slice.
-
1:19
Now, you could also use substring.
-
1:22
Or substr.
-
1:24
Both of those methods would also work fine.
-
1:27
I'm going to go ahead and switch back to the slice method.
-
1:31
The first parameter for the slice method is the begin index.
-
1:34
The zero based index at the string extraction should begin with.
-
1:39
The second parameter is the end index.
-
1:42
The index that the string extraction should end with.
-
1:45
It's worth noting that the character at this index won't be included.
-
1:49
Let's take a look at the string for Sunday.
-
1:52
So S is at an index of 0.
-
1:55
U is at an index of 1.
-
1:58
And n is at an index of 2.
-
1:59
So we want to extract Su, but not n.
-
2:05
So with the slice method, we'll supply the 2.
-
2:08
Meaning that we want to select up to but not including the index of 2.
-
2:14
Now that I have my dayAbbreviation, I just pushed it onto the dayAbbreviations array.
-
2:20
So dayAbbreviations.push(dayAbbreviation).
-
2:26
And that's my solution.
-
2:28
Now, we can leave it just as it is, or we could simplify it.
-
2:33
We can do that by eliminating the intermediate variable, (dayAbbreviation).
-
2:38
To do that, let's cut this code and place it inside of the call to the push method.
-
2:44
Then we can eliminate this line of code.
-
2:47
And we can actually eliminate the code block itself.
-
2:51
There.
-
2:53
That looks a little cleaner, doesn't it?
-
2:55
Ready for the next challenge?
-
2:56
We'll see you in a bit with my solution.
You need to sign up for Treehouse in order to download course files.
Sign up