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

Brian Schmitz
Brian Schmitz
11,167 Points

Sorting string from shortest to longest challenge

Can someone please help me with this challenge. I'm not sure how to sort them to show the shortest string to the longest string. The directions are as follows:

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.

Thanks

2 Answers

Ben Lee
Ben Lee
9,791 Points

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

That should arrange the strings in ascending order or shortest to longest. And if you wanted to sort them from the longest to shortest, you would return b.length - a.length. Hope this helps!

Brian Schmitz
Brian Schmitz
11,167 Points

Thanks Ben. How about for this challenge where it is asking me to return length for arrayCounter or 0 where there an undefined, string, or number value. I have this code but it isn't passing:

function arrayCounter (array) { if (typeof array === 'undefined', [1,2,3], 'string') { return 0;

      return array.length;
    }
  }
Ben Lee
Ben Lee
9,791 Points

Hmmm, I'm not 100% sure about this but let's give this a shot.

Instead of using commas to separate your arguments 'undefined', [1,2,3], 'string'), try using the "or" operator ||. So it should look something like this:

function arrayCounter(array) { if (typeof array === 'undefined' || [1, 2, 3] || 'string') { return 0; }

Let's hope this works!

Brian Schmitz
Brian Schmitz
11,167 Points

No such luck there, thanks for the look though. I posted it so we will see. Thanks