【问题标题】:Sorting data using array使用数组对数据进行排序
【发布时间】:2017-12-10 12:27:22
【问题描述】:

这是我的 components.ts。 我想编写一个按计数对数组进行排序的函数,我将在 html 中使用排序后的数组数据来创建图表。

import { Component } from '@angular/core';
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html',
})
export class Dashboard {
  private data = [];
  constructor() {
    this.data = [{
      'maxTime': 30041,
      'minTime': 6453,
      'avgTime': 18949,
      'count': 4,
      'requestRouteTemplate': 'api/GetUserPostponesCountReport',
      'requestMethod': 'POST',
    },
  ...
  }
]

【问题讨论】:

  • 只是对答案的补充。我推荐有一个名为Lodash 的简洁库。使用 lodash 你可以简单地data = _.sortBy(data, 'count');

标签: json angular sorting typescript ng2-charts


【解决方案1】:

你可以使用sort函数

this.data.sort(function(a,b){
    return a.count - b.count;
});

供参考 - sort

用于调整-plunker

【讨论】:

    【解决方案2】:

    在您希望按计数显示数据顺序的 dashboard.html 文件中实现此功能

    像这样:

    <tr  *ngFor="#friend in friends| orderBy : ['count']"">
          <td>{{friend.name}}</td>
          <td>{{friend.phone}}</td>
          <td>{{friend.count}}</td>
    </tr>
    

    【讨论】:

    • 只是一个想法 - OP 希望数据在 JS 中的函数中排序,因为图表需要数据,orderBy 可能不可用。
    【解决方案3】:
    this.data.sort(function (a, b) {
      return a.count - b.count;
    });
    

    来源:https://developer.mozilla.org/hu/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

    或者只是一个 ES6 快捷方式:

    data.sort((a, b) => a.count - b.count ); 
    

    因为在一行中你不需要{} 也不需要return 并且还允许箭头功能。

    【讨论】:

    • 或者只是一个 ES6 快捷方式:data.sort((a, b) => a.count - b.count );因为在一行中你不需要 {} 也不需要 return 并且还允许箭头功能
    猜你喜欢
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2012-11-14
    相关资源
    最近更新 更多