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 trialSlavik Ostapenko
Courses Plus Student 12,480 PointsCan't get thrue the challenge
Here's the challange: 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've tried a few things. This was the "closest", but still far a way from a right answer:
saying2.sort(function (a,b) {
return saying2[a].length-saying2[b].length;
});
//HELP, please
4 Answers
J Scott Erickson
11,883 PointsYou have the right sort of idea. But the variables are a bit off. I'm the function you have a and b as parameters.
function ( a, b ) {
return a.length - b.length;
}
The in depth explanation of the mechanics of a and b is a little long. But just consider a and b to be the words in the array being compared.
Dave McFarland
Treehouse TeacherIn this example, the parameters a
and b
represent the arrays passed to the anonymous function. In other words, you don't access the saying2
array inside the function:
saying2.sort(function (a,b) {
return a.length-b.length;
});
Dino Paškvan
Courses Plus Student 44,108 Pointsa
and b
parameters of the compare function are actual array elements, not index positions, so you want to return a.length - b.length
from the function.
Slavik Ostapenko
Courses Plus Student 12,480 PointsThanks a lot, everrybody.