The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

How to sort an array by string value

posted on 25.1.2023 by Below Surface in "JavaScript"

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

Tags:

javascript
es6
array
sorting
method
typescript
react

More posts of this category

Convert a date to dd.mm.yyyy (German date layout)

An easy one line method to convert your date into the german standard

JavaScript