'How to sort an array using values from an enum?

I want to sort elements of an array using an enum, I would like to know how to do it, I have tried with a switch statement with no success.

   const enum Order {
      Start = 'Start',
      Run = 'Run',
      End = 'End',
    }

    const predicate (a, b) => // TODO 

    const data = [Order.End, Order.Run, Order.Start]

    const result = data.sort(predicate)

    // wanted result is: // Start, Run, End


Solution 1:[1]

I created a function in typescript based on previous answer to order objects from an enum.

export function sortByStatus(a: Element, b: Element): number {
    const map = new Map<Status, number>();
    map.set(Status.DONE, 0);
    map.set(Status.ERROR, 1);
    map.set(Status.PROCESSING, 2);
    map.set(Status.NONE, 3);

    if (map.get(a.status) < map.get(b.status)) {
        return -1;
    }
    if (map.get(a.status) > map.get(b.status)) {
        return 1;
    }
    return 0;
}

Furthermore, I include a mini test to check its functionality.

it('check sortByStatus', () => {
    expect(sortByStatus(a, b)).toBeLessThanOrEqual(1);
    expect(sortByStatus(b, a)).toBeGreaterThanOrEqual(-1);
    expect(sortByStatus(a, a)).toBe(0);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dharman