Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
like image 947
Hypenate Avatar asked Oct 21 '25 17:10

Hypenate


1 Answers

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])
like image 108
adiga Avatar answered Oct 24 '25 08:10

adiga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!