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 trialNeslee Rodillo
19,615 Pointsreally do not understand task 2 of 2
help, I am able to pass
task 1 of 2: On about line 18, modify 'saying1' so it's in the opposite order.
Just fine
but the task 2 of 2: Sort the 'saying2' array, on about line 19, so that the words are listed in length order. The shortest first. Use the 'length' property on the strings in the sort function.
- I keep going around in circles.
my solution for task 2 is
saying2.sort(function("length"){});
I know I may be missing something simple but I have watched the video so many times as it only explains the compare function with relation to numbers not strings or text.
2 Answers
Dino Paškvan
Courses Plus Student 44,108 PointsIf you think about it, you're not really using the compare function with strings. Length of a string is a numerical property — it's a number. You are sorting strings, yes, but you are sorting them based on a numerical property, one that you can access using dot notation (string.length
).
So, the compare function works like this:
saying2.sort(function(a,b){
return a.length - b.length;
});
It's as if you're sorting numbers, but instead of subtracting elements directly from one another, you are subtracting their lengths and returning the result of that operation.
Neslee Rodillo
19,615 PointsThank you for your help Dino :)