我想订购一个 Array
的对象,其中对象包含一个枚举属性。
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'
};
在我的数组 _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;
}
问题是我按枚举名称获取数组顺序:
代替:
如何按照枚举的“顺序”对数组进行排序?而不是按字母顺序排列?
答案 0 :(得分:1)
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;
});
这将对您的数组进行排序,顺序键存储在 MyEnum 中。