【问题标题】:How can i sort array using AngularJs or Javascript?如何使用 AngularJs 或 Javascript 对数组进行排序?
【发布时间】:2016-04-12 17:21:32
【问题描述】:

一旦用户做出选择或当我们从后端渲染数据时,我想按字母顺序排序和显示数组,我想按字母顺序显示fullName$scope.selecedControlOwnerng-click 事件处理程序,一旦用户从模式窗口中选择所有者并单击确定ng-click 事件触发并在父窗口上显示值现在我想在这里触发排序。

$scope.controlOwnerObj.workerName 是将值绑定到父窗口的 ng-model。

有没有使用 AngularJs 或原生 Javascript 的解决方案?

ctrl.js

$scope.selectedControlOwner = function() {
      $scope.controlOwnerObj.workerName= $scope.selectedOwners.map(function (owner) { return owner.fullName; }).join(';');
     };


    $scope.selectedOwners = [{
            "workerKey": 46958,
            "fullName": ,"Kumari, Swapna"
        }, {
            "workerKey": 746,
            "fullName": "Mike Piero",
        }, {
            "workerKey": 150918,
            "fullName": "A J, Jyothish",
        }],

【问题讨论】:

标签: javascript arrays angularjs sorting


【解决方案1】:

使用javascript内置的sort函数

$scope.selectedOwners = [{
            "workerKey": 46958,
            "fullName": ,"Kumari, Swapna"
        }, {
            "workerKey": 746,
            "fullName": "Mike Piero",
        }, {
            "workerKey": 150918,
            "fullName": "A J, Jyothish",
        }],
$scope.selectedOwners.sort(function(a, b) {
  return a.fullName.localeCompare(b.fullName);
});

【讨论】:

  • 这里的问题甚至是数组排序我将$scope.controlOwnerObj.workerName 分配给 ng-model ,我们是否需要一些具有该属性的东西在这里有点混淆
  • @hussain 如果您想要拥有已排序的所有者名称字符串,您必须在 map 之前对数组进行排序,例如 .sort(function(a, b) {return a.fullName.localeCompare(b.fullName);}).map(function (owner) { return owner.fullName; }).join(';');
【解决方案2】:

我将只使用纯 JavaScript,因为你给了我们一个选项

这会将它们从低到高排序

  var arr = [12, 213, 3, 121, 44, 12];
    arr.sort(function (x, y) {
        return x > y;
    })

它不会返回一个新数组。

结果:[3、12、12、44、121、213]

这会将它们从高到低排序

    arr.sort(function (x, y) {
        return x < y;
    })

结果 [213, 121, 44, 12, 12, 3]

【讨论】:

    【解决方案3】:

    您好,您可以使用 angularjs orderby..

    https://docs.angularjs.org/api/ng/filter/orderBy

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-27
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-17
      • 1970-01-01
      相关资源
      最近更新 更多