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

Allison Guthrie
Allison Guthrie
6,781 Points

Using .sort(function (a,b)... with the .length method

Hi there, I can't seem to figure the second question out. Right now, I have:

Here's the task:
"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."

Here's my answer: saying2.sort(function (a,b){ saying2.length });

Here's the comment about it not passing:

Bummer! The 'saying2' was 'The,quick,brown,fox,jumped,over,the,lazy,dog's,back' not 'The,fox,the,over,lazy,back,quick,brown,dog's,jumped'.

I know this isn't right, but I can't seem to figure out how to combine both parts of this task. Please help. Thanks so much!

1 Answer

George Kuka
George Kuka
2,673 Points

Ok so you're passing in two arguments into the function ~ a & b. These are the arguments that you'll use the length method on to determine how it's sorted.. So the function should look like this...

function( a, b ) { return a.length - b.length; };

The sort function is looking for a -1, 0, or 1 on the return. Here's a link that helped me understand it a bit better.
http://www.javascriptkit.com/javatutors/arraysort.shtml

Allison Guthrie
Allison Guthrie
6,781 Points

Thanks so much, George. Makes sense now. Thanks also for the link. I really appreciate it. :)