Imagine we have an array of objects:
const arr = [ { name: "Tim" }, { name: "Jim" }, { name: "Kim" } ]
One easy way to sort them by the first letter of their names is to do this (ES6):
arr.sort((a, b) => a.name.localeCompare(b.name));
Please note that this will change the original array, so assigning this to a new variable may not make sense.
If you use TypeScript and want to use this string method in a React app for example, the TypeScript compiler will not accept the implicit any type for a and b. Let's have another example to solve this:
We have created the type declaration Category in our typings.ts file and it looks like this:
export type Category = { _id: string; categoryName: string; categoryUrl: string; }
Now we want to sort an array which contains Category objects. In our React app, we just need to import the Category type object:
import { Category } from '../typings';
Then we can apply this type definition for our .sort() method:
categoryArray.sort((a: Category, b: Category) => a.categoryName.localeCompare(b.categoryName))