简体   繁体   English

按枚举顺序而不是值对数组进行排序

[英]Sort array by enum order and not value

I would like to order a Array of object, where object contain a enum properties.我想订购一个 object Array ,其中 object 包含一个枚举属性。

export enum MyEnum {
  FIXTERM1W = 'FIXTERM_1W',
  FIXTERM2W = 'FIXTERM_2W',
  FIXTERM1M = 'FIXTERM_1M',
  FIXTERM2M = 'FIXTERM_2M',
  FIXTERM3M = 'FIXTERM_3M',
  FIXTERM6M = 'FIXTERM_6M',
  FIXTERM1Y = 'FIXTERM_1Y',
  FIXTERMDEFAULT = 'FIXTERM_DEFAULT',
  FIXTERMWA = 'FIXTERM_WA',
  ONCALL24H = 'ONCALL_24H',
  ONCALL48H = 'ONCALL_48H',
  ONCALLWA = 'ONCALL_WA'
};

In my array _myvalue I have list of myobject , each myobject contain a properties code of type MyEnum :在我的数组_myvalue我有myobject列表,每个myobject都包含一个MyEnum类型的属性代码:

get xxx(): (Yyyy) {
    if (this._myvalue && this._myvalue.myobject && this._myvalue.myobject.length > 0) {
      this._myvalue.myobject = sortBy(this._myvalue.myobject,
        [function (o: any): any {
          return o.code;
        }]);
    }
    return this._myvalue;
}

The problem is that I get the array order by enum name:问题是我通过枚举名称获取数组顺序:

  1. 1W 1W
  2. 1M 1M
  3. 1Y 1年
  4. ... ...

Instead of:代替:

  1. 1W 1W
  2. 2W 2W
  3. 1M 1M
  4. ... ...

How I can order my array by the "order" of my enum?如何按枚举的“顺序”对数组进行排序? and not a alphabetical order?而不是按字母顺序?

    const order = [];
    for (let key in MyEnum) {
          order.push(key);
    }
    const newArray = myArray.sort((a, b) => {
          const index1 = order.findIndex(key => MyEnum[key] === a.code);
          const index2 = order.findIndex(key => MyEnum[key] === b.code);
          return index1 - index2;
    });

This will sort your array, in the order keys are stored in MyEnum.这将对您的数组进行排序,按顺序键存储在 MyEnum 中。

You could use:你可以使用:

MyObject.sort((a, b) => Object.values(MyEnum).indexOf(a.code) - Object.values(MyEnum).indexOf(b.code))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM