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

Code Challenge: Methods 2, Part 2 of 2

This is what the challenge is asking:

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.

This is what I have entered as my code:

      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(a, b) {
              saying2.length();
              return a-b;
      });

I cannot find another forum post that answer the question and I cannot think of anything else to do.

Whoever can help, thank you!

3 Answers

try this

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

Stone -

Remember our goal here on the forum is give help not answers, next time try giving an explanation and/or a hint instead.

Need more explanation on the distinction check this out.

Stone, thank you, I appreciate your help. That was the solution. I actually tried something very similar and I see why it didn't work. This was my attempt which was similar to yours:

<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(a, b){
    return a.length() - b.length();
  });
</script>

I was using parentheses after .length for no good reason.

Can someone explain why my first attempt did not work, regardless of the unnecessary parentheses? This is the "bummer" message returned upon my first attempt. The same message is returned without parentheses after .length.

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

Whats going on here?

In JavaScript length is a property not a function, so it's a.length is valid JS while a.length() is in not valid JS.

Thank James! You've helped me here as well as on other forum post I've looked at.