基于多个条件的Javascript数组排序(一次迭代)

马切洛

我有很多车:

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某种方式使用

谢恩

您可以创建一个映射函数来确定您的优先级,而只需减去排序中的标准化值即可。

const Condition = { New: 1, Used: 2 };

const cars = [
  {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 = {
  make: "Ford",
  model: "Panamera",
  age: 4,
  condition: Condition.New
};

const prioritize = (car, query) => {
  if (car.make === query.make) return 4;
  if (car.model === query.model) return 3;
  if (car.age === query.age) return 2;
  if (car.condition === query.condition) return 1;
  
  return 0;
};

const sorted = cars.sort((a, b) => {
  const prioA = prioritize(a, searchQuery);
  const prioB = prioritize(b, searchQuery);

  return prioB - prioA;
});

console.log(JSON.stringify(sorted, null, 2));

如果您希望排序适用于多种条件,例如首次制造和制造,则可以添加一个简单的递归检查并增加优先级:

const prioritize = (car, query) => {
  const { make, model, age, condition } = query;

  if (car.make === make) return 4 + prioritize(car, { model, age, condition });
  if (car.model === model) return 3 + prioritize(car, { age, condition });
  if (car.age === age) return 2 + prioritize(car, { condition });
  if (car.condition === condition) return 1;

  return 0;
};

在这里,您只需检查其他查询选项。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章