In java we can use Comparable interface to sort Objects by fields. Like in the below example we're sorting Fruit based on the quantity

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;

    }   
}

I want to know is there any way to implement this sort of implementation in Angular(Typescript) also ?

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

    constructor() {}
}

1 Answers

0
Enol García González On

The operation is similar to java, but it is not necessary to use the interface. If you want a fruit to be comparable, implement the method. Structurally the compiler will not do checks and at run time it will work:

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

However it occurs as in Java. To sort an array in Java you use the sort method of the collection and you can pass a comparator. The way to order elements in typescript is identical. The sort method of the collection is called and a comparator method is passed as a parameter. Here is an example:

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);