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

Darrin Banfield
Darrin Banfield
8,244 Points

Problem getting the challenge

it asks to sort by length starting with shortest.
this is what I have: (saying 2) 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 Math.length;

please help this is so frustrating.

2 Answers

dan schmidt
dan schmidt
2,576 Points

Arrray.prototype.sort is one of worse parts of javascript and a common source of bugs and confusion, so don't feel to frustrated by it. L)

Here is some reference regarding the behavior of sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

So, firstly there is no property length on Math. What you need to do is pass two values into the comparison function to compare. You would compare the lengths of them in this case. If the first designated parameter's length is shorter than the second's, you return a -1 or else you return 1

var compare = function (x, y) {
  if (x.length < y.length) { return -1; }
  return 1;
}
Darrin Banfield
Darrin Banfield
8,244 Points

Thanks for your insight and solution. However, to pass the challenge i had to use the sort function. But by reading the information you sent i was able to figure it out. Thanks a lot!!!