I have an array of cars:
enum Condition {
New = 1,
Used = 2
}
type Car = {
make: string;
model: string;
age: number;
condition: Condition;
};
const cars: Car[] = [
{id: "1", make: "BMW", model: "E3", age: 12, condition: Condition.Used},
{id: "2", make: "Audi", model: "A8", age: 4, condition: Condition.Used},
{id: "3", make: "Mercedes", model: "SLK", age: 0, condition: Condition.New},
{id: "4", make: "Ford", model: "CMAX", age: 3, condition: Condition.Used},
{id: "5", make: "Ford", model: "BMAX", age: 0, condition: Condition.New},
{id: "6", make: "Porsche", model: "Panamera", age: 0, condition: Condition.New},
]
And I have a search query:
const searchQuery: Car = {
make: "Ford",
model: "Panamera",
age: 4,
condition: Condition.New
}
I want to have a sorted array based on these rules:
- items that exactly matches the make ("Ford") comes first
- the rest that exactly matches the model ("Panamera") comes second
- the rest that matches the condition of age = 4
- the rest that is of condition New,
- and at last any item that does not pass any of the tests
First what I did was to filter the array that matched the make and then the model then the age, etc...
And then merged the resulting arrays to a final array (also filtered out duplicates that passed multiple criteria), but that require iterating over the cars as many times as the number of criteria I have.
So I wondered if there is a better way to do it in one pass? Maybe using .sort somehow?