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

Andrew Probert
Andrew Probert
1,862 Points

I'm really not sure how to do the second challenge here? How to sort the strings in the array by length.

All I know about the .length property is using it on the array to determine how many objects are in the array.

3 Answers

Daniel Wilson
Daniel Wilson
5,929 Points

You need to create a function that sorts by length. In the video he uses the argument (a - b) to sort by numerical order, so just use (a.length - b.length) to sort the strings by length instead of their numerical value.

Dan Mirda
Dan Mirda
3,992 Points

You have to pass a function to the sort method that tells the sort method how to compare any two values from the array. The method needs to return a positive number if the first element is greater than the second. A negative value if it is less than the second or zero if they are the same.

Use the string property "somestring".length to your advantage when creating this function.

hector gonzalez
hector gonzalez
14,109 Points

I'm stuck on the same challenge I have this code:

'''saying2= saying2.sort(function(a,b){ a.lenght -b.length; }); ''' and the output is correct i got this: Original array: 'The,quick,brown,fox,jumped,over,the,lazy,dog's,back' Sorted array: 'The,fox,the,over,lazy,back,quick,brown,dog's,jumped'.

but still i got it wrong