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

Michael Baker
Michael Baker
7,731 Points

stuck

answer please....

Question please....

James Barnett
James Barnett
39,199 Points

> Question please....

Or more accurately which question ...


Michael Baker -

While you successfully used the content tag feature to link this forum post to a particular code challenge.

Nearly all of the code challenges (including this one) have multiple steps, so what are the instructions for the step of you are having issues with.

2 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

The first question use the .reverse() method which you attach to the array itself.

The second question uses the .sort() method which has a basic format like this:

myArray.sort(function(a,b) {
   //comparison between a and b in here
  // return <0, 0 or >0
});

The function you supply inside the .sort() method is used to compare elements in an array. In this example, a represents one element in an array and b represents the next element in the array. The function needs to return one of three values:

  1. a number LESS THAN 0
  2. the number 0
  3. a number greater than 0
  • If the number is LESS than 0, then a is sorted BEFORE b

  • If the number is 0, then a and b stay in the same spot in relation to each other

  • If the number is GREATER than 0, then b is placed BEFORE a

For this Code Challenge, you need to compare the lengths of strings in an array. You can get the length of a string with the .length property. You can use some simple math to get the proper return value for the .sort() function:

a.length - b.length;
  • If the string a is shorter than b then the answer is less than 0 (so a will go before b).

  • If the string a is longer than b then the answer is greater than 0 (so b will go before a).

  • If the string a is the same length as b then the answer is 0 (so they stay in the same position`).

Hope these hints help.

Michael Baker
Michael Baker
7,731 Points

Sorry for not being more specific... I was stuck on the second challenge; wasn't sure where/how to use the .length property to measure the strings. Dave's answer helped me figure it out.... in the function, instead of return a-b; change it to: return a.length - b.length; THANKS!!! Michael