【问题标题】:Angular natural sort array of objects角度自然排序对象数组
【发布时间】:2017-12-05 20:23:53
【问题描述】:

我对 Angular 很陌生,所以也许我只是在寻找错误的东西,但我似乎无法在任何地方找到一个简单的答案。

假设我有一个对象数组:

[
  {Label: "UDP 128B Flood", ...},
  {Label: "UDP 512B Flood", ...},
  {Label: "UPD 1514B Flood",...},
  {Label: "HTTP Excessive GET",...} 
]

这个数组在下拉列表中显示为选项:

<option *ngFor="let profile of Profiles" [value]="profile.Label">{{profile.Label}}</option>

我想对这些对象进行排序以确保它们按字母数字顺序显示。

【问题讨论】:

    标签: angular typescript angular5 natural-sort


    【解决方案1】:

    使用array.prototype.sort 函数

    let sorted = [
      {Label: "UDP 128B Flood"},
      {Label: "UDP 512B Flood"},
      {Label: "UDP 1514B Flood"},
      {Label: "HTTP Excessive GET"} 
    ].sort((a, b) => a.Label.localeCompare(b.Label));
    
    console.log(sorted);

    【讨论】:

    • 这个很接近,但是“UDP 1514B Flood”排在“UDP 512B Flood”前面
    • 那是因为它实际上是“UPD 1514B”。编辑:我已为您将其更改为 UDP,因此它现在按您期望的顺序排序
    【解决方案2】:

    Javascript : natural sort of alphanumerical strings

    从这个帖子中找到答案。

    profiles.sort((as, bs) => {
    var a: any, b: any, a1: number, b1: number, i= 0, n: number , L,
        rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
    if(as.Label=== bs.Label) return 0;
    a= as.Label.toLowerCase().match(rx);
    b= bs.Label.toLowerCase().match(rx);
    L= a.length;
    while(i<L){
        if(!b[i]) return 1;
        a1= a[i],
            b1= b[i++];
        if(a1!== b1){
            n= a1-b1;
            if(!isNaN(n)) return n;
            return a1>b1? 1:-1;
        }
    }
    return b[i]? -1:0;
    

    });

    【讨论】:

      【解决方案3】:

      试试这个,希望对你有帮助。

      var array=[
        {Label: "UDP 128B Flood", ...},
        {Label: "UDP 512B Flood", ...},
        {Label: "UPD 1514B Flood",...},
        {Label: "HTTP Excessive GET",...} 
      ]
      array.sort(this.sortArray);
      sortArray(){ if(b.Label.toString().toLowerCase() <a.Label.toString().toLowerCase()) { return -1; }
      if(b.Label.toString().toLowerCase() >a.Label.toString().toLowerCase()) { return 1; } }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-10
        • 2023-04-09
        • 2017-09-27
        • 2020-08-04
        • 1970-01-01
        • 2011-04-18
        • 1970-01-01
        相关资源
        最近更新 更多