Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!