简体   繁体   中英

Sort array by enum order and not value

I would like to order a Array of object, where object contain a enum properties.

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 :

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
  2. 1M
  3. 1Y
  4. ...

Instead of:

  1. 1W
  2. 2W
  3. 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.

You could use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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