【发布时间】:2020-05-17 19:33:59
【问题描述】:
我有一系列汽车:
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},
]
我有一个搜索查询:
const searchQuery: Car = {
make: "Ford",
model: "Panamera",
age: 4,
condition: Condition.New
}
我想要一个基于这些规则的排序数组:
- 与品牌(“福特”)完全匹配的商品排在第一位
- 与模型完全匹配的其余部分(“Panamera”)排在第二位
- 其余符合年龄=4的条件
- 其余的都是新的,
- 最后是任何未通过任何测试的项目
首先我做的是过滤与品牌匹配的数组,然后是模型,然后是年龄,等等......
然后将生成的数组合并到最终数组(也过滤掉通过多个条件的重复项),但这需要迭代cars 的次数与我拥有的条件数量一样多。
所以我想知道是否有更好的方法可以一次性完成?也许以某种方式使用.sort?
【问题讨论】:
-
请在此处添加您的最小代码/尝试
-
您是否尝试过使用过滤功能,例如 array.filter(item => item.make === query.make).filter(item => item.model === query.model) ........等等
-
或者你可以在 1 次迭代中完成 array.filter(item => item.make === query.make && item.model === query.model) 等等
-
@Alopwer 这不是我想要的。这只会过滤汽车以一次匹配所有条件,从而产生一个空数组,因为没有符合所有条件的项目。
标签: javascript arrays sorting