angular - 角管 - 排序数字
问题描述
非常努力地弄清楚如何对数字进行排序。我正在处理一个 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)
解决方案
在这里查看堆栈闪电战。也许您有错字或其他问题,但考虑到我们正在谈论字符串:
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();
}
}
推荐阅读
- javascript - 如何在 Apache Echarts 图表上标记一个点?
- gpgpu - 苹果金属内核的变化不会改变执行时间
- javascript - 点击添加视频描述
- artifactory - XRay 使用自签名证书失败
- python - 将数据注册到 json 时出现问题仅注册数字而不是字符串
- javascript - Firebase action.payload 返回 id,但数据未定义
- python - Python在输出每个结果之前打印csv列值而不重复
- ios - 以编程方式自定义 UITabBar 不规则形状
- flutter - 将横向图像转换为肖像(旋转图像)并保存 - Flutter
- settings - Envoy 设置短链接