Eri*_*rik -1 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"},
]
Run Code Online (Sandbox Code Playgroud)
我需要对该数组进行排序以按顺序获取元素(第一个 - 订单,第二个 - 详细信息,第三个 - 购买):
console.log(source.sort(function () {
// todo: ?
}))
Run Code Online (Sandbox Code Playgroud)
预期结果:
[
{"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"},
]
Run Code Online (Sandbox Code Playgroud)
如何编写排序函数才能得到预期的结果?
您可以创建一个对象来保存每个类别的优先级,然后根据该对象对其进行排序。
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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
766 次 |
| 最近记录: |