skip to Main Content

I have a JS file with about 1,000 variables that looks like this:

export const FruitOrange: React.FC = () => (
    <Trans id="fruit.orange">Orange</Trans>
);
export const FruitApple: React.FC = () => (
    <Trans id="fruit.apple">Apple</Trans>
);

I want to sort all the variables in this to be in alphabetical order.

In other words, I want to sort the variable declarations so that FruitApple comes before FruitOrange.

How can I do this?

I just need to reformat the file once; any tool that can do this automatically is acceptable; I just don’t want to hand-sort 1,000 variables.

2

Answers


  1. Use MS Word for example

    Copy and paste your code in.

    • Control H, search for ^p (the trailing space is important, so you only capture the indented lines) and ‘Replace All’ them with nothing.

    • Control H, search for ^p} and ‘Replace All’ them with }.

    • Now each definition is on a single line. In the Home icon-bar thingy, go to the Paragraph section and press Sort (the A->Z icon).

    Then copy-paste it back into your code editor, such as VS Code, and get it to reformat.

    This should work as long as any multi-line definitions have indentation (which again, VS Code and others should do for you).

    Login or Signup to reply.
    1. Make all the variables single line with regex(.* toggle) replacer (ctrl+h)
      n(?!export) -> <<NEWLINE>>
    export const FruitOrange: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.orange">Orange</Trans> <<NEWLINE>>);
    export const FruitApple: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.apple">Apple</Trans> <<NEWLINE>>);
    
    1. Select all text(ctrl-a) and use VSCode command Sort Lines Ascending from the command pane (ctrl-shift-p)
    export const FruitApple: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.apple">Apple</Trans> <<NEWLINE>>);
    export const FruitOrange: React.FC = () => ( <<NEWLINE>>    <Trans id="fruit.orange">Orange</Trans> <<NEWLINE>>);
    
    1. Restore your newlines back
      <<NEWLINE>> -> n
    export const FruitApple: React.FC = () => (
        <Trans id="fruit.apple">Apple</Trans>
    );
    export const FruitOrange: React.FC = () => (
        <Trans id="fruit.orange">Orange</Trans>
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search