DEV Community

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

Posted on

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)