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

Tammy Herrera
Tammy Herrera
4,070 Points

saying2 sort by length

can someone provide the formula for this? I don't thing there was enough information provided in the lesson.

3 Answers

Can you post the problem you're referring to? This question needs more information.

Tammy Herrera
Tammy Herrera
4,070 Points

Sort 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!

Hi 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;