arrays - How-come sort 将遍历数组中的所有元素,其中函数仅比较 2 个元素?
问题描述
我使用此代码能够对名称数组进行排序。代码检查 a 和 b 并返回 -1、0 或 1。我可以理解这些值将名称按顺序排列,但我无法弄清楚这段代码如何确保数组被评估和排序以获得完整的排序列表。
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe implements PipeTransform {
transform(array: any, field: string): any[] {
if (!Array.isArray(array)) {
return;
}
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
}
解决方案
考虑一个Array
array = [{'make': 'BMW'}, {'make': 'Audi'}]
array.sort((a: any, b: any) => {
if (a[field] < b[field]) { // field will be the property of object to sort on
return -1; // Sort Ascending 'a' < 'b' true then it'll enter this
} else if (a[field] > b[field]) {
return 1; // If this is -1 and the above is 1, Sort descending
} else {
return 0; // Default return value (no sort)
}
});
推荐阅读
- javascript - 正则表达式捕获 [] 之间的内容
- objective-c - 读取文件的 com.apple.progress.fractionCompleted 属性
- xpath - max() 输出正确的数字,count()="right number" 选择正确的节点,但是 count()=max() 失败
- spotfire - Spotfire:将值更改为字符串并保留其他值
- reactjs - Web 组件发出的事件可能无法通过 React 渲染树正确传播:我可能会遇到哪些可能的问题?
- c# - 在 C# WPF 中同时运行的多个 DispatcherTimer 实例
- javascript - 粘性导航栏的问题不会像应该那样滚动
- c++ - UB 何时发生,是否会使所有先前签订的合同无效?
- c - 如何调用函数
- c# - 未调用 OnStartCommand/OnCreate