按人工顺序对JavaScript数组进行排序 [英] Sort JavaScript Array in Artificial Order
本文介绍了按人工顺序对JavaScript数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 REST
查询返回的数组,该数组代表了多步骤生产过程中的项目数.
I have an array returned by a REST
query that represents the number of items in a multi-step production process.
var steps = [
{ name:'Package', value:3},
{ name:'Assemble', value:1 },
{ name:'Ship', value:7},
{ name:'Preprocess', value:9 },
{ name:'Paint', value:5 }
];
我想按流程的顺序对它们进行排序,如下所示:
I'd like to sort them in the order of the process, like this:
- 预处理
- 绘画
- 组装
- 包装
- 船
我使用Underscore进行其他字母数字排序,但是我无法弄清楚这一点.
I have other alphanumeric sorts that I am doing with Underscore but I cannot figure this one out.
推荐答案
您可以使用所需位置的对象作为带有位置数值的对象.然后按此值排序.
You could take an object for the wanted order with numerical values for the position. Then sort by this values.
var steps = [{ name: 'Package', value: 3 }, { name: 'Assemble', value: 1 }, { name: 'Ship', value: 7 }, { name: 'Preprocess', value: 9 }, { name: 'Paint', value: 5 }],
order = { Preprocess: 1, Paint: 2, Assemble: 3, Package: 4, Ship: 5 };
steps.sort(({ name: a }, { name: b }) => order[a] - order[b]);
console.log(steps);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于按人工顺序对JavaScript数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文