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 trialMartin Argosino
1,447 PointsIn JavaScript Foundations, I'm stuck on Arrays/Methods-2, Challenge Question 2. Is there somewhere I can get the answer?
How do you sort 'the values of an array', from shortest to longest, based on the 'length of each individual value'?
The values are all strings, and apparently, I'm supposed to use the 'length property' in the 'sort' function.
This is the actual array in the challenge question:
var saying2 = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog's", "back"];
Stuck!
3 Answers
Julian Gutierrez
19,201 Pointssaying2.sort(function(a,b){
return a.length-b.length;
})
Martin Argosino
1,447 PointsIt's simple now seeing your answer, but I could not come up with that conversion on my own. Thanks Julian.
Molly Black
6,352 PointsI had -
saying2.sort(function(a, b) { return a.length > b.length; });
- which, in my console works no problem, but the code challenge wouldn't accept it. Is there a reason the "-" is better to use than the > ?
Noel Deles
8,215 PointsJust a beginner as well but my hunch is that a.length > b.length returns a boolean value whereas using - returns an int value? Now why the latter is better than the former I have no idea.
Daniel Stockham
10,277 PointsI think Noel makes a good point. When you use that comparison operator you are only finding a boolean value when javascript is perfectly capable determining the order according to the length through a math function.