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

Christoffer Boye-Hansen
Christoffer Boye-Hansen
3,810 Points

Java: Missing the 'length' property on your strings

So my challenge is: 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.

My script currently looks like this: <script> var saying1 = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]; var saying2 = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog's", "back"]; saying1.reverse(); saying2.sort(function() { });

Then I thought I could do like this, but then it says that task 1 is no longer passing.

<script> var saying1 = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]; var saying2 = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog's", "back"]; saying1.reverse(); saying2.sort(function() { return saying2.length(); });

How do I call .length inside the function?

2 Answers

Hi Christoffer,

I believe the video ran through how to sort numbers in an array.

It was something like:

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

So the sort method would pass in two numbers from the array into the compare function and the compare function would return a positive, negative, or zero value to indicate the relative order of a and b

You want to do something very similar here. Except that 2 strings from the array are going to be passed in and you want to subtract their lengths.

saying2.sort(function(a, b) {
    return a.length - b.length;
});
Bob Sutherton
Bob Sutherton
20,160 Points

I had to ask on that one too!