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 trialJames Barnett
39,199 Points>
Question please....
Or more accurately which question ...
While you successfully used the content tag feature to link this forum post to a particular code challenge.
Nearly all of the code challenges (including this one) have multiple steps, so what are the instructions for the step of you are having issues with.
2 Answers
Dave McFarland
Treehouse TeacherThe first question use the .reverse()
method which you attach to the array itself.
The second question uses the .sort()
method which has a basic format like this:
myArray.sort(function(a,b) {
//comparison between a and b in here
// return <0, 0 or >0
});
The function you supply inside the .sort()
method is used to compare elements in an array. In this example, a
represents one element in an array and b
represents the next element in the array. The function needs to return one of three values:
- a number LESS THAN 0
- the number 0
- a number greater than 0
If the number is LESS than 0, then
a
is sorted BEFOREb
If the number is 0, then
a
andb
stay in the same spot in relation to each otherIf the number is GREATER than 0, then
b
is placed BEFOREa
For this Code Challenge, you need to compare the lengths of strings in an array. You can get the length of a string with the .length
property. You can use some simple math to get the proper return value for the .sort()
function:
a.length - b.length;
If the string
a
is shorter thanb
then the answer is less than 0 (soa
will go beforeb
).If the string
a
is longer thanb
then the answer is greater than 0 (sob
will go beforea
).If the string
a
is the same length asb
then the answer is 0 (so they stay in the same position`).
Hope these hints help.
Michael Baker
7,731 PointsSorry for not being more specific... I was stuck on the second challenge; wasn't sure where/how to use the .length property to measure the strings. Dave's answer helped me figure it out.... in the function, instead of return a-b; change it to: return a.length - b.length; THANKS!!! Michael
Riley Hilliard
Courses Plus Student 17,771 PointsRiley Hilliard
Courses Plus Student 17,771 PointsQuestion please....