AngularJS $filter('orderBy') strange sorting

Looks like AngularJS $filter("orderBy") works not the same way as Array.prototype.sort. I wrote example for this problem:

Template:

<div ng-app="app" ng-controller="ctrl">
    <div>arr1 angular </br>{{ arr1ang }}</div>
    <div>arr2 angular </br>{{ arr2ang }}</div>
    <div>arr1 js </br>{{ arr1js }}</div>
    <div>arr2 js </br>{{ arr2js }}</div>
</div>

Controller:

angular.module('app', []);

function ctrl ($scope, $filter) {
    arr1 = [
      {value: "AA"}, 
      {value: "AB"}, 
      {value: "aa"}, 
      {value: "ab"}
    ];
    arr2 = [
      {value: "d"}, 
      {value: "D"}, 
      {value: "w"}, 
      {value: "e"}, 
      {value: "i"}, 
      {value: "O"}, 
      {value: "o"}, 
      {value: "r"}
    ];

    $scope.arr1ang = $filter('orderBy')(arr1, "value");
    $scope.arr2ang = $filter('orderBy')(arr2, "value");

    function comp(a,b){
        if (a.value > b.value)
            return 1;
        else if (b.value > a.value)
            return -1;
        else
            return 0;
    }

    arr1.sort(comp);
    arr2.sort(comp);
    $scope.arr1js = arr1;
    $scope.arr2js = arr2;
}

angular
  .module('app')
  .controller('ctrl', ctrl);

Result:

arr1 angular
[{"value":"AA"},{"value":"aa"},{"value":"AB"},{"value":"ab"}]
arr2 angular
[{"value":"d"},{"value":"D"},{"value":"e"},{"value":"i"},{"value":"O"},{"value":"o"},{"value":"r"},{"value":"w"}]
arr1 js
[{"value":"AA"},{"value":"AB"},{"value":"aa"},{"value":"ab"}]
arr2 js
[{"value":"D"},{"value":"O"},{"value":"d"},{"value":"e"},{"value":"i"},{"value":"o"},{"value":"r"},{"value":"w"}]

I made a Codepen example about it here.

I don't understand something or it is a bug in AngularJS?

Answers:

Answer

Angularjs orders it alphabetically case-insensitive. In JavaScript string comparison is case-sensitive.

One solution is to convert all values to lower-case or upper-case strings before comparison.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.