Sorting an Array of Objects in Typescript

Implementation

The sort() method helps deal with arrays in Javascript that contain primitive types, but you'll need to pass a custom function to the method to sort an array of objects. I'm going to walk through a simple helper function that I used to sort arrays of objects in TypeScript!

function sortBy<T>(selector: (value: T) => string | number, array: T[]): T[] {}

First let's define a function that takes two arguments: a selector function and an array. We can use generics to build a method signature shown below. This is a high order function because it accepts another function as a parameter.

The selector returns a string or a number from our object type T that will be used in the comparison when sorting an array. T is the object type we're sorting, giving us the flexibility to use this method on any kind of object. And then we return the new sorted array of type T[].

function sortBy<T>(selector: (value: T) => string | number, array: T[]) { // sort accepts a function that returns either 1, 0 or -1 return array.sort((a, b) => { const aValue = selector(a); const bValue = selector(b); if (aValue < bValue) { return -1; } if (aValue > bValue) { return 1; } return 0; }); }

The JavaScript sort function accepts a function that will use the result of the selector function to determine the order of each element in the array. See the implementation below.

Why not just use sort?

You can use sort by passing a custom function that compares to objects. But this function abstracts away some of the details. Instead of having to remember to return 1, 0 or-1, you only need to define a selector function. And in my opinion, this is a much cleaner solution.