如何根据类别对数组进行排序?

时间:2018-12-04 21:22:13

标签: javascript sorting

我有以下对象数组:

var source =  [
  {"name": "title_1", "category": "order"},
  {"name": "title_2", "category": "purchase"},
  {"name": "title_3", "category": "order"},
  {"name": "title_4", "category": "detail"},
  {"name": "title_5", "category": "order"},
  {"name": "title_6", "category": "purchase"},
]

我需要整理该数组以按顺序获取元素(第一-订单,第二-详细信息,第三-购买):

console.log(source.sort(function () {
   // todo: ?
}))

预期结果:

[
  {"name": "title_1", "category": "order"},
  {"name": "title_3", "category": "order"},
  {"name": "title_5", "category": "order"},
  {"name": "title_4", "category": "detail"},
  {"name": "title_2", "category": "purchase"},
  {"name": "title_6", "category": "purchase"},
]

如何编写排序函数以获得预期结果?

1 个答案:

答案 0 :(得分:4)

您可以创建一个包含每个类别优先级的对象,然后根据该对象对其进行排序。

const source =  [
  {"name": "title_1", "category": "order"},
  {"name": "title_2", "category": "purchase"},
  {"name": "title_3", "category": "order"},
  {"name": "title_4", "category": "detail"},
  {"name": "title_5", "category": "order"},
  {"name": "title_6", "category": "purchase"},
];

const priority = {
   order: 3,
   detail: 2,
   purchase: 1,
};

const r = source.sort((a, b) => priority[b.category] - priority[a.category]);
console.log(r);