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

HELP PLEASE

I don't know how to sort the array by the length of the strings. Thanks

1 Answer

Stone Preston
Stone Preston
42,016 Points

here is an example from the mozilla docs:

var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
    return a - b;
});

which sorts an array of numbers. we want to sort by the length of strings, so we will need to use .length on a and b

so it should look something like this:

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

a.length - b.length sorts it in ascending order b.length - a.length sorts it in descending order

Thanks mate!