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 Loops, Arrays and Objects Tracking Multiple Items with Arrays Iterating through an Array

Dale Parr
Dale Parr
2,214 Points

help with iterating an Array and sorting the numbers in a descending order

Hi,

I have noticed that .sort() puts 10 and 100 next to each other because of the 1.

Could anyone give me a pointer on this?

Thank you Dale

script.js
var temperatures = [100,90,99,80,70,65,30,10];
for ( var i = 100; i > 10; i -= 1);
console.log(temperatures.sort());
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

3 Answers

Dale Parr
Dale Parr
2,214 Points

I have also tried this...

var temperatures = [100,90,99,80,70,65,30,10]; temperatures.splice(1, 2, 99, 90); for ( var i = 100; i > 10; i -=1); console.log(temperatures);

The output in console.log look correct, however, the challenge still throws an error.

this is the console.log output. var temperatures = [100,90,99,80,70,65,30,10]; temperatures.splice(1, 2, 99, 90); for ( var i = 100; i > 10; i -=1); console.log(temperatures); VM174:4 (8) [100, 99, 90, 80, 70, 65, 30, 10] 0: 100 1: 99 2: 90 3: 80 4: 70 5: 65 6: 30 7: 10 length: 8 proto: Array(0)

Try this :

var points = [40, 100, 1, 5, 25, 10];
console.log(points.sort(function (a, b) { return b - a }));

When the sort() method compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the compare function(40,100).

The function calculates 40-100, and returns -60 (a negative value).

The sort function will sort 40 as a value lower than 100.

https://www.w3schools.com/jsref/jsref_sort.asp

Dale Parr
Dale Parr
2,214 Points

Hey Maxime, Thanks for taking the time to help with this code challenge....it's really appreciated. Part of the requirement is to include a loop. This is the challenge "Use a for or while loop to iterate through the values in the temperatures array from the first item -- 100 -- to the last -- 10. Inside the loop, log the current array value to the console."

Its had me stumped. :-)