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 trialacespotan
7,725 Pointssorting an array by comparing the length of an array element to another...
Hi there,
I'm kind of stuck on this particular question. I am understanding the problem as to 'sorting an array by comparing the length of an array element to another', which means I need to pull the length of each index of the array, 'saying2[i].length', and not the length of the array 'saying2.length'. Saying2.length will only return the number of elements in the array. If I am correct in understanding the question, I am having some problems sorting the array[index].length. My steps taken are:
- pull the saying2[i].length by looping through each element in the array using a for loop
- compare saying2[i].length to one another to determine which is greater
- display the sort order by saying2[i].length
for(var i = 0; i <= saying2.length; i++){
console.log(i.toString()); i.sort(function(a,b){ return a-b; }); }
I think I'm confusing myself, please help! much appreciated. ~ Grace
3 Answers
Chris Shaw
26,676 PointsHi,
I think you're over thinking the question a little bit, the sort method doesn't require any wrapper functionality such as a for loop, all it's simply asking for is the below.
saying2.sort(function(a, b) {
return a.length - b.length;
});
Juan Ferreira
47,991 PointsGrace saying2 is an Array object. The Array object has a sort function. Therefore you can simply sort saying2 by "saying2.sort();".
This, however, wouldn't sort the Array based on length of strings. Instead the sort function sorts strings alphabetically by default. To go about handling this you'll need to pass a function as an argument to the sort function.
Like such:
saying2.sort(function(a,b){ return <SORT ALGORITHM>; });
Where <SORT ALGORITHM> would be what you want your sorting algorithm to be based on.
Let me know if you need me to explain what the <SORT ALGORITHM> should be to proceed forward. I figured I not give you the sorting algorithm but direction in solving the problem.
acespotan
7,725 PointsChris + Juan, Thank you both very much... both of you helped me clear my head and rethink the problem. Chris, you are correct in saying I'm over thinking the question. Thanks again.