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

Lisa Rioni
Lisa Rioni
12,372 Points

Task 2 of 2 in the Methods 2 section

Task 2 of 2 in the Methods 2 section: 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 answer: saying2.sort(function (a, b) { var alength = sayings2[a]; var blength = sayings2[b]; return alength.length - blength.length; });

Error: Oops! It looks like Task 1 is no longer passing.

2 Answers

Hello,

I think your code is not right and more specifically var alength = sayings2[a].

The arguments a and b in the function are the the elements in the array saying 2. You can't access an element by it's value. You have to use the key: saying2[0] for example.

The task is to get every two pairs of elements and compare their lenghts.

So if you want to use your code, it has to look like this:

saying2.sort(function (a, b) { 
        var alength = a.length; // getting the length of the first element
        var blength = b.length; // getting the length of the next element
        return alength - blength; 
      });;

But it will be much easier to do it like this:

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

Hope that helps and good luck!

Lisa Rioni
Lisa Rioni
12,372 Points

Thanks tihomirvelev! That worked.