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 trialZach Saul
11,156 PointsJava Script Foundations Code Question: I want to sort strings in an array by length - why ant I use compare?
I cannot figure out this code challenge - i'm sure it'll be easy to answer for those who have already been coding with JS for some time:
the task is to sort the strings by length into a new sorted array:
var saying2 = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog's", "back"];
this was my proposed solution using the comparison method:
saying2.sort(function (a.length, b.length) {
return a.length-b.length;
}
Why am I wrong? i don't understand, and am wondering if i'm close
<!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.length, b.length) {
return a.length-b.length;
}
</script>
</body>
</html>
3 Answers
Ken Alger
Treehouse TeacherZach;
In the code in your comment your brackets are not properly placed, but you have the correct idea.
saying2.sort(function(a, b) {
return a.length - b.length;
});
Your original function was accepting two input variables with names of a.length
and b.length
. Generally speaking you can accept inputs into your function as whatever name you would like, so you could have called them foo
and bar
, or whatever. Including JavaScript properties along with the variable foo.length
, for example, as input variables into a function creates, um... interesting results.
Make any sense?
Happy holidays,
Ken
Ken Alger
Treehouse TeacherZach;
Take the .length
out of the function declaration, it should look more like function(a,b)
.
Ken
Zach Saul
11,156 Pointsso then it should read: saying2.sort(function (a, b)) { return a.length-b-length; } i'm still getting an error.
I just want to understand what I'm doing wrong.
Alan Fidelino
12,846 PointsHi Zach,
Your almost there, just delete the extra ")" after (a,b) and you're good to go. saying2.sort(function (a, b){ return a.length-b-length; };