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 trial

JavaScript JavaScript Foundations Arrays Methods: Part 2

In 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
Julian Gutierrez
19,201 Points
saying2.sort(function(a,b){
        return a.length-b.length;
 })

It's simple now seeing your answer, but I could not come up with that conversion on my own. Thanks Julian.

Molly Black
Molly Black
6,352 Points

I 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
Noel Deles
8,215 Points

Just 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
Daniel Stockham
10,277 Points

I 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.