loading...

TS sortĀ helper

github logo 惻1 min read

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;
  });
}

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.

twitter logo DISCUSS
Classic DEV Post from Jun 23 '19

What Advice Would You Give Your 20-year-old Self?

If you could go back in time, what advice would you give your 20-year-old self?

Jamie Neubert Pedersen profile image
Full-Stack developer, and a paragliding enthusiast!