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 trialMichael Bardeggia
1,659 PointsStumped by Task 2
I'm stumped by: 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.
2 Answers
Dave McFarland
Treehouse TeacherJavaScript gives us a .sort()
method for arrays. It takes a function which compares two items in the array. If the value returned is less than 0 then the first item is placed before the second item; if the value returned is greater than 0 then the two items switch places in the array; and if the return value is 0, the positions of the two values isn't changed.
saying2.sort(function(a,b) {
return (a.length - b.length);
});
In this example, a
and b
in the function represent two strings in the array. By comparing their .length
properties you can figure out which word is longer than the other. For example, say you compared two strings "Goodbye"
and "Hello"
. By accessing the length of each you'll see that the first string is 7 characters long and the second is 5 characters long: 7 - 5 is 2, that's more than zero so the two strings switch places. Hope that helps.
Michael Bardeggia
1,659 PointsThanks Dave. I was close. Cheers, Mike