Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  91] [ 6]  / answers: 1 / hits: 189324  / 11 Years ago, thu, march 7, 2013, 12:00:00

How can i get a reversed array in angular?
i'm trying to use orderBy filter, but it needs a predicate(e.g. 'name') to sort:



<tr ng-repeat=friend in friends | orderBy:'name':true>
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>


Is there a way to reverse original array, without sorting.
like that:



<tr ng-repeat=friend in friends | orderBy:'':true>
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>

More From » arrays

 Answers
48

I would suggest using a custom filter such as this:



app.filter('reverse', function() {
return function(items) {
return items.slice().reverse();
};
});


Which can then be used like:



<div ng-repeat=friend in friends | reverse>{{friend.name}}</div>


See it working here: Plunker Demonstration






This filter can be customized to fit your needs as seen fit. I have provided other examples in the demonstration. Some options include checking that the variable is an array before performing the reverse, or making it more lenient to allow the reversal of more things such as strings.


[#79771] Wednesday, March 6, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bryantc

Total Points: 455
Total Questions: 96
Total Answers: 110

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
bryantc questions
Fri, Aug 13, 21, 00:00, 3 Years ago
Tue, Mar 30, 21, 00:00, 3 Years ago
Fri, Jun 5, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;