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 trialNorman Craig
14,018 Pointssort using length
I'm working on the challenge that requires I use "sort"with length inside. I feel like I'm very close, but can't get a correct answer. Can anyone correct my code?
Norm
<!DOCTYPE html>
<html lang="en">
<head>
<title> JavaScript Foundations: Arrays</title>
<style>
html {
background: #FAFAFA;
font-family: sans-serif;
}
</style>
</head>
<body>
<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.sort(function (a, b)
{
saying2.length;
return a-b;
}
);
</script>
</body>
</html>
1 Answer
eck
43,038 PointsYou are indeed pretty close, you are just not getting the length for the correct strings.
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.sort(function(a, b){
// Get the lengths of the strings that will be compared by the sort() method and subtract then from one another.
// The result is sent to the sort method, which will do some magic and arrays will be organized.
return a.length - b.length;
});
If you don't like magic, you can uncover the truth of sort() here.
Norman Craig
14,018 PointsNorman Craig
14,018 PointsErik Thank you sooo much. I fought with that for longer than I care to share!