按人工顺序对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:

  1. 预处理
  2. 绘画
  3. 组装
  4. 包装

我使用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; }