0

I have this Js method but I can't to implement a reverse loop

$scope.organizeByMonth = function () {    
    for (var i in $scope.incidents) {

        var month = new Date($scope.incidents[i].upload_date).getMonth();    
        if (!monthIncidents[month]) {

            monthIncidents[month] = {    
                name: $scope.months[month],
                incidents: []
            };
        }
        var incident = $scope.incidents[i];    
        incident.index = i;    
        monthIncidents[month].incidents.push(incident);
    }
};

how can I show the same objects in reverse :/

suspectus
  • 14,884
  • 8
  • 41
  • 53
  • 1
    See http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea if $scope.incidents is an array (which it looks like it is because `push` is used for a similar name). If it is an array it can be easily reversed prior to iterating it; or the 'explicit for' form can be trivially used. – user2864740 Jul 20 '15 at 21:12

3 Answers3

3

You can't do a reverse loop with the for in syntax - it also doesn't matter. Objects in JavaScript are unordered.

tymeJV
  • 99,730
  • 13
  • 150
  • 152
1

The closest to a reverse for..in.. loop would be to get the object keys and iterate backwards over them:

var object = { a: 1, b: 2, c: 3 };
var keys = Object.keys(object);
for(var i = keys.length - 1; i >= 0; i--) {
    console.log(keys[i], object[keys[i]]);
}

http://jsfiddle.net/1oztmp2e/

Sebastian Nette
  • 5,878
  • 2
  • 15
  • 17
0

Why would you like to reverse the for loop? Is it only for display purpose?

If so, I am assuming you are using ng-repeat for displaying the records. Should that be the case, you can use a custom reverse filter.

Or if you need the array reversed for a different reason, simply use Array.reverse after populating the array

Community
  • 1
  • 1
Michele Ricciardi
  • 2,087
  • 11
  • 17