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 trialTammy Herrera
4,070 Pointssaying2 sort by length
can someone provide the formula for this? I don't thing there was enough information provided in the lesson.
3 Answers
Twiz T
12,588 PointsCan you post the problem you're referring to? This question needs more information.
Tammy Herrera
4,070 PointsSort saying array on line 19, so the words are listed in length order. Shortest first. Use the 'Length' property on the strings in the sort function.
var saying2 = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog's", "back"];
saying2.sort(function (a, b){ return saying2.length });
I have tried and had not gotten the correct result. I'm at a loss with this question. Can you assist me with the answer? thnx!
Jason Anello
Courses Plus Student 94,610 PointsHi Tammy,
The example given in the video was to sort numbers.
my_array.sort(function(a, b) {
return a - b;
});
So 2 numbers from the array are passed in for a
and b
and by subtracting them we're able to return either a positive, negative, or zero value. Depending on how a
and b
relate to each other.
You want to do something similar for the array of strings in this problem. Two strings from the array will be passed in for a
and b
. However, we can't subtract strings. We're trying to sort by string length so we should subtract their lengths.
return a.length - b.length;