# Sort array by enum order and not value

## Issue

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

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

How I can order my array by the "order" of my enum ? and not a alphabetical order ?

## Solution

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