首页 > 解决方案 > 角管 - 排序数字

问题描述

非常努力地弄清楚如何对数字进行排序。我正在处理一个 ngFor 循环,我想对我的一些值进行排序。我正在使用不带冒号的时间码(电影/电视)数字。像这样的数字

01002000 01003000 01000012

我想使用管道按 asc 顺序对这些进行排序。对于我的生活,我似乎无法让它工作

我已经创建了一个管道,我正在尝试


export class SortTimecodePipe implements PipeTransform {
  transform(value, direcion): any {

    return value.sort();
  }
}

我也知道 sort 处理字符串,所以我也尝试过给 sort 函数一个参数。


export class SortTimecodePipe implements PipeTransform {
  transform(value, direcion): any {
    function compare(a, b) {
      return a - b;
    }

    return value.sort(compare);
  }
}

这些选项都不起作用。排序没有发生。

你能提供任何帮助吗?

- - - - 编辑 - - - -

返回的数据实际上是一个对象数组,它们看起来像这样

[
{"timecodeIn": 01000020, "timecodeOut": 01000010, "Reason": "Alt Line", "Line": "Hey there"},
{"timecodeIn": 01000005, "timecodeOut": 01000007, "Reason": "Extra", "Line": "You"}
]

I'm tyring to ngFor this array of objects, sorted by the 'timecodeIn' property.

Thanks for the note on sorting numbers like this over strings, I can see how it would fail now. Also, wondering if sorting in the component is better than the view (pipe)

标签: angularsortingpipe

解决方案


在这里查看堆栈闪电战。也许您有错字或其他问题,但考虑到我们正在谈论字符串:

numbersStr = ['01002000', '01003000', '01000012'];

或数字

numbers = [1002000, 1003000, 1000012];

然后在html中

<div>
  <h4> Sorting strings array </h4>
  <ul>
    <li *ngFor="let number of numbersStr | sortStringsPipe">{{number}}</li>
  </ul>
  <h4> Sorting number array </h4>
  <ul>
     <li *ngFor="let number of numbers | sortPipe"> 
       {{number}}</li>
  </ul>
<div>

以下过滤器完美运行。

import {PipeTransform,Pipe} from '@angular/core'

@Pipe({
  name:'sortStringsPipe',
  pure:false
})
export class ShortStringsPipe implements PipeTransform {


transform(value:any[]):any{
  return value.sort();
}

}

推荐阅读