2

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 ?

2 Answers 2

2
    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.

Sign up to request clarification or add additional context in comments.

Comments

1

You could use :

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.