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 trialDarren Kynaston
Courses Plus Student 15,610 PointsI'm stuck on how to write the code to answer this question... Sort the saying2 array so that the words are listed in....
<html>
<p>
Q: Sort the 'saying2' array, on about line 19,
so that the words are listed in length order.
The shortest first. Use the 'length' property
on the strings in the sort function.
</p>
<div>
<h1>JavaScript Foundations</h1>
<h2>Arrays: Methods Part 1</h2>
<script>
var saying1 = ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"];
var saying2 = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog's", "back"];
saying1.reverse();
saying2.;
</script>
</div>
</html>
2 Answers
Dino Paškvan
Courses Plus Student 44,108 PointsYou are supposed to use the .sort()
method and pass it the anonymous compare function. That function takes two parameters: a
and b
.
Those parameters will be array elements that are being compared.
Since you'll be sorting the array based on the length of the elements, your compare function should return a.length - b.length
.
It's just like the example in the video, but instead of subtracting b
from a
, you have to subtract their lengths.
Darren Kynaston
Courses Plus Student 15,610 PointsHi Dino,
I'm not really understanding how that code works, I have tried a few different pieces of code but I still can't get it to accept. I don't know where to input the lengths (am I missing something???)
I understand that saying2 is a variable containing a list of "strings". I understand that you can apply .sort(); to sort them as "strings" But I then don't understand how I apply the .length into the function.....
???
I understand the code that is applied to numeric values to show ascending numeric order... but I don;t understand how to code in .length into this example - it's keeps rejecting my attempts.
saying2.sort(function (a,b){
return a-b;
});
Darren Kynaston
Courses Plus Student 15,610 Pointssaying2.sort(function (a,b){
return a.length - b.length;
});
:)