首页 > 解决方案 > 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;
  }
}

标签: arraysangularsortingreturnpipe

解决方案


考虑一个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)
       }
    });

推荐阅读