DEV Community

Cover image for TS sort helper
Jamie Neubert Pedersen
Jamie Neubert Pedersen

Posted on

3 2

TS sort helper

Instead of writing a sort function every-time, I have created a neat little helper function, and I wanted to share it with you all.
As it uses generics it works on any Array of elements that have keys.

sort<T>(list: T[], sortBy: keyof T, direction: 'asc' | 'desc' = 'asc') {
  const dir = direction === 'asc' ? 0 : 2;
  return list.sort((a, b) => {
    if (a[sortBy] > b[sortBy]) {
      return 1 - dir;
    }
    if (a[sortBy] < b[sortBy]) {
      return dir - 1;
    }
    return 0;
  });
}
Enter fullscreen mode Exit fullscreen mode

The cool thing is that it get's type hints while you are writing, so after specifying the list to work on, Intellisense prompts you for the sortBy parameter solely on what keys exist in the type.

Alt Text

Let me know if you find this helpful.

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay