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 trialJacqueline Wilson
2,078 PointsJavaScript Array Sort
Getting an error when I use sort function that return array length of list the words in the array by length order with the shortest first.
saying2.sort(function(){
return saying2.length
}
4 Answers
Adam Sackfield
Courses Plus Student 19,663 PointsTry this
saying2.sort(function (a, b) {
return a.length - b.length;
});
Jacqueline Wilson
2,078 PointsThanks, I didnot realize you use the substraction for stings.
Jacqueline Wilson
2,078 PointsThanks that is a great explaination
Errin E. Johnson
22,458 PointsGreat explanation! thank you!
Dave McFarland
Treehouse TeacherDave McFarland
Treehouse TeacherAdam's answer is right. When you use a sorting function, the 2 arguments you pass to it represent 2 items in the array:
a
is one array item andb
is another array item. To compare their lengths you just need to use thelength
property of each:a.length - b.length