角度:如何按属性对对象列表进行排序?

时间:2019-05-13 14:41:47

标签: java angular typescript sorting

在Java中,我们可以使用Comparable接口按字段对对象进行排序。像下面的示例一样,我们根据数量对水果进行排序

public class Fruit implements Comparable<Fruit>{

    private String fruitName;
    private String fruitDesc;
    private int quantity;

    public Fruit(String fruitName, String fruitDesc, int quantity) {
        this.fruitName = fruitName;
        this.fruitDesc = fruitDesc;
        this.quantity = quantity;
    }

    public String getFruitName() {
        return fruitName;
    }
    public void setFruitName(String fruitName) {
        this.fruitName = fruitName;
    }
    public String getFruitDesc() {
        return fruitDesc;
    }
    public void setFruitDesc(String fruitDesc) {
        this.fruitDesc = fruitDesc;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int compareTo(Fruit compareFruit) {

        int compareQuantity = ((Fruit) compareFruit).getQuantity(); 
        return this.quantity - compareQuantity;

    }   
}

我想知道还有没有办法在Angular(Typescript)中实现这种实现?

export class Fruit {
    fruitName: string;
    fruitDesc: string;
    quantity: number;

    constructor() {}
}

1 个答案:

答案 0 :(得分:0)

该操作类似于java,但是没有必要使用该接口。如果要使水果具有可比性,请实施该方法。从结构上讲,编译器将不执行检查,并且在运行时将起作用:

compareTo(compareFruit: Fruit): int {
    return this.quantity - compareFruit.quantity;
}

但是它像Java中那样发生。要使用Java对数组进行排序,请使用集合的sort方法,然后可以传递比较器。在打字稿中对元素进行排序的方式是相同的。调用集合的sort方法,并将比较器方法作为参数传递。这是一个示例:

let fruits = [];
fruits.push(new Fruit(...));
fruits.push(new Fruit(...));
fruits.push(new Fruit(...));
fruits.push(new Fruit(...));

fruits.sort((fruitA, fruitB) => fruitB.quantity - fruitA.quantity);
相关问题