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

victor guia
victor guia
8,098 Points

Solution to Task 2 of 2 for Array Methods Part 2

My solution to the problem was to change the elements in the array saying 2 to represent the length of the strings..

saying2 = [saying2[0].length, saying2[1].length, saying2[2].length, saying2[3].length,saying2[4].length, saying2[5].length, saying2[6].length, saying2[7].length, saying2[8].length, saying2[9].length];

Then I sorted them by saying2.sort()

I tried this out on the javascript console and I got the correct sorted array.[3, 3, 3, 4, 4, 4, 5, 5, 5, 6]. Next, I sorted in again by

saying2.sort(function(a, b) { return a - b; })

and I got the same correct result.

I tried this out in the workspace but it returned an error for "lack of function"

So inserted a function by typing the same sort method with function above and I get the error "The saying2 is 3,5,5,3..... not 'The' 'fox' 'the' 'over'.....

If my solution in the workspace is wrong then why did I get the correct result in the Javascript console/

3 Answers

Hi Victor,

I'm not sure if an answer was deleted here or not. The main forum page indicates this has a best answer but currently that answer is not appearing here.

In your solution you have sorted the lengths of the strings which is not what the challenge is asking for. You want to sort the strings by length. Your output should be the original strings rearranged based on their length.

saying2.sort(function(a, b) {
        return a.length - b.length;
      });

Similar to how you would sort numbers by subtracting them, a - b, you can sort strings by length by subtracting their lengths.

victor guia
victor guia
8,098 Points

thanks. I got confused.

you are welcome