2

I created an array with numbers, but in the method sort() not ordering it correctly in ng-repeat.

eg

$scope.order = ['1', '10', '11', '22', '29', '2'];

eg

<li ng-repeat="key in order.sort()">{{key}}</li>

see how ordered

1 10 11 2 22 29

not

1 2 10 11 22 29

eg http://jsfiddle.net/YWsJ7/

3
  • You have created an array of strings and they sort alphabetically. Delete the quotes to make it an array of numbers: [1,10,11,...]. Commented Apr 13, 2014 at 19:12
  • @NikosParaskevopoulos the result will be the same. Commented Apr 13, 2014 at 19:16
  • @KyleNeedham You are right, I never saw this (insane) fine print in Array.sort(); the comment that it is an array of strings however still holds. Sort an array of numbers by providing the simple comparator to sort: [1, 10, 11, 22, 29, 2].sort(function(a,b){return a-b;}) Commented Apr 13, 2014 at 19:20

2 Answers 2

2

You can use orderBy filter with expression parameter. In the following example each value of the array will be passed to parseInt function and then values will be compared using <, > and =:

JavaScript

function mainCtrl($scope) {  
    $scope.parseInt = parseInt;
    $scope.order = ['1', '10', '11', '22', '29', '2'];
}

HTML

<li ng-repeat="key in order | orderBy : parseInt ">{{key}}</li>

Fiddle: http://jsfiddle.net/5kRRc/3/

Documentation on orderBy filter

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work when the collection is not an array. For example: $scope.numList = {"1":{name:"1"}, "2":{name:"2"}, "10":{name:"10"}, "21":{name:"21"}}; and <li ng-repeat="key in numList | orderBy:parseInt">{{key.name}}</li>
1

You can make use of the angular filter method:

 <li ng-repeat="key in order | orderBy: 'value'">{{key.value}}</li>

JSFIDDLE

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.