简体   繁体   中英

Order array by name of enum instead of value

I have an enumeration:

export enum Foo{
    AA= 0,
    ZZ= 1,
    AB= 2,
    ER = 5
}

I want my Bars , which contain the enum as a property foo , to be sorted on the name of the enum (AA, AB, ER, ZZ), and not on the numerical value (0, 1, 2, 5).

I'm using lodash to help me but I can't seem to get it to work:

const orderedBars = _.orderBy(unorderedBars, 'foo');

You could use localeCompare to sort them based on the string value:

unorderedBars.sort((a,b) => Foo[a.foo].localeCompare(Foo[b.foo]))

Demo on Typescript playgorund (Click on "Run")

If the property is string and you want to sort it based on the numerical value, you could sort it like this:

unorderedBars.sort((a, b) => Foo[a.foo] - Foo[b.foo])

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