The Complete Guide to Sorting Arrays of Objects in Typescript (2024)

When we create an application or websites we need to sort array data frequently. And in Typescript we often need to sort arrays with strings, numbers or Booleans. But, there may be also the case when we need to sort more complex arrays of objects and not just the plain values.

Sorting is a great thing and it allows you to quickly find, compare and rank objects in any array based on your condition. Sorting array of objects allows us to order the objects based on one or most of their properties.

Lets take an example. Suppose we have an array of person objects with properties name, age and job. Now, sorting them alphabetically by name would order all the People with similar names together. And similarly, sorting by age from lowest or highest (or vise versa) will order them accordingly.

Here are most common use cases that i have came across for sorting arrays of objects in TypeScript.

  • Ordering and Organizing fetched data from an API to be more readable
  • Ranking some items to show the most relevant first
  • Putting items in alphabetical, numerical, or desired order
  • Sorting DOM elements to dynamically update the UI
  • Sorting products by price or rating for an ecommerce site

There are other many real world complex objects that you may come across and need sorting. Here is the full guide that covers most basic and most advance techniques for sorting array of objects with Typescript.

Basic Array Sorting in Typescript

As you may know already, the easiest way to sort an array in Typescript is using the built-in .sort() method. This method allows to sort elements of array and mutate the original array.

For example:

let numbers = [5, 3, 2, 4, 1];numbers.sort();console.log(numbers); // [1, 2, 3, 4, 5]

.sort() method sorts values as strings by default. This works flawlessly for sorting numbers and strings but can show incorrect results when you try to sort other data types.
You can customize the way of sorting elements by function .sort(). The compare function takes two arguments (a and b) and :

  • It will return a negative number if a should come before b
  • It will return a positive number if b should come before a
  • It will return 0 if a and b are equal

Here is an example to sort numbers from smallest to largest:

let numbers = [5, 3, 2, 4, 1];numbers.sort((a, b) => a - b);console.log(numbers); // [1, 2, 3, 4, 5]

The above example passes a compare function that subtracts b from a, and returns a negative number if a is less than b. This compare function gives you a lot of flexibility in how arrays are sorted in Typescript.

Sorting Arrays of Primitives

You can use the sort() method for sorting arrays of primitive values like strings, numbers, and booleans in TypeScript.
Here is an example to sort an array of strings:

let strings = ['c', 'a', 'b'];strings.sort();// ['a', 'b', 'c']

In above the sort() method will sort the strings alphabetically in ascending order by default.

You can similarly sort the numbers too.

let numbers = [3, 1, 2];numbers.sort();// [1, 2, 3]

This will sort the numbers in ascending order as well.

Note: For descending sorts, you can pass a compare function to sort() - we’ll cover this more in the “Sorting in Descending Order” section below.

Sorting Arrays of Objects

Objects don’t have a default sort order like strings or numbers. You will need to provide a compare function that specifies which property to sort on when sorting arrays of objects in TypeScript. With this compare function you will tell TypeScript how to compare the objects.

Here is an example:

interface Person {name: string;age: number;}const people: Person[] = [{name: "Jack", age: 30},{name: "Mary", age: 25},{name: "John", age: 40}];people.sort((a, b) => {return a.age - b.age;});

In this example we are sorting the array of Person objects by the age property in ascending order. This compare function subtracts the age of person A from person B to get a positive or negative number to find out the sorting order. This allows you full control over how TypeScript should sort an array of objects.

Sort by a Single Property

You can sort an array of objects by a single property like name or by age. In TypeScript the Array.sort() method accepts a compare function through which you can compare the name or age property of objects.

For example:

interface Person {name: string;age: number;}const people: Person[] = [{name: "John", age: 20},{name: "Mary", age: 25},{name: "Mike", age: 30}];people.sort((a, b) => {if(a.name < b.name) return -1;if(a.name > b.name) return 1;return 0;});console.log(people);// [// {name: "John", age: 20},// {name: "Mary", age: 25},// {name: "Mike", age: 30}// ]

In this example the compare function in sort method takes two Person objects a and b. It compares the name property of a and b alphabetically and then it returns -1 if a should come before b, 1 if a should come after b and 0 if a and b are equal.

Similarly, You can sort by any property like age or date of birth. To do that you will only need to change the compare function property.

Sort by Multiple Properties

Also, You can sort any array of objects by multiple properties. For example, if you need to sort the array by name first, then by age:

interface Person {name: string;age: number;} const people: Person[] = [{name: "Bob", age: 30},{name: "Alice", age: 25},{name: "Bob", age: 20}]; people.sort((a, b) => {if (a.name < b.name) return -1;if (a.name > b.name) return 1;if (a.age < b.age) return -1;if (a.age > b.age) return 1; return 0;}); console.log(people);// [// {name: "Alice", age: 25},// {name: "Bob", age: 20},// {name: "Bob", age: 30}// ]

This example first compares the name property and then sort it alphabetically. When it is done with sorting the names, it will compare the age property and sort them numerically.

So, you can add as many comparison scenarios as you need like above. The array will be sorted by each property in order.

Sorting in Descending Order

If you need to sort an array of objects in descending order, you have to provide a compare function to the sort() method that reverses the default sort order.

Here is an example:

interface User {name: string;age: number;} const users: User[] = [{name: "John", age: 30},{name: "Jane", age: 20},{name: "Jim", age: 25}];users.sort((a, b) => {if (a.age > b.age) return -1;if (a.age < b.age) return 1;return 0;}); console.log(users);// [ {name: "John", age: 30}, {name: "Jim", age: 25}, {name: "Jane", age: 20} ]

In this example, the comparison happens between a and b. If a comes after b in ascending order then it returns -1 which indicates that a should come before b in descending order. And similarly, if a comes before b in ascending order, it returns 1 that means that a should come after b in descending order.

If both are equal it will return 0 and that will maintained by their relative order.

You can simplify above compare function by using the ternary operators and can do it in one line:

users.sort((a, b) => a.age > b.age ? -1 : a.age < b.age ? 1 : 0);

It will show the same result as previous function.

Case-Insensitive Sorting

In many cases, we need to sort array of objects that are case-insensitive. eg, “aBc” comes before “XYZ” in ascending order by default.
and to do a case-insensitive sort, we need to convert the strings to lowercase before comparing them in the compare function.

For example:

interface Person {name: string;} let people: Person[] = [{name: "John"},{name: "paul"},{name: "George"},{name: "Ringo"}]; people.sort((a, b) => {let nameA = a.name.toLowerCase();let nameB = b.name.toLowerCase(); if (nameA < nameB) {return -1;}if (nameA > nameB) {return 1;} return 0;});

This converts name property of this object to lowercase before the comparison, so the end result is:

[ {name: "George"}, {name: "John"}, {name: "paul"}, {name: "Ringo"} ]

This approach works well for simple case-insensitive sorting of strings.
In case if you need to do more complex sorting, you can use a library like lodash which has built-in case-insensitive sorting functions.

Sorting Nested Objects

When sorting arrays of objects that contain nested objects, we need to access the nested properties in the compare callback function.

For example, if we have an array of objects with a nested address object:

const users = [{name: 'John',address: {city: 'New York'}},{name: 'Jane',address: {city: 'Los Angeles'}}];

We can sort it by accessing nested city property and then sort it like below:

users.sort((a, b) => {if(a.address.city < b.address.city) {return -1;}if(a.address.city > b.address.city) {return 1;}return 0;});

Inside the compare function, we can use a.address.city and b.address.city to access the nested city property and then compare the values. This process works for objects nested at any depth - we just chain the property accessors together to drill down into the nested structure. By accessing the nested properties in the compare callback, we can sort arrays of objects with any level of nesting.

Conclusion

In Typescript coding, it is very important to know sorting arrays and primitives like strings, numbers, and dates. But the most valuable thing is ability to sort arrays of objects by one or more properties. Sorting helps to organize complex data structures in a logical way and makes it easier to work within our code.

The Complete Guide to Sorting Arrays of Objects in Typescript (2024)

FAQs

How do you sort an array with objects in TypeScript? ›

In TypeScript, you can use the Array. prototype. sort() method to sort an array of objects by a property value. The sort() method takes a comparator function as its argument, which should return a negative, zero, or positive value depending on the order in which the elements should be sorted.

How do you sort an array of objects? ›

The sort() method of Array instances sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

What is the return type of sort in TypeScript? ›

The sort() method in TypeScript sorts the elements of an array and returns the sorted array. By default, it sorts an array in ascending order. It can take an optional compareFunction to define the sort order, allowing for custom sorting logic.

How to sort an array in React TypeScript? ›

How to Sort an Array in TypeScript ?
  1. Method 1: Using sort method.
  2. Method 2: Spread Operator.
  3. Method 3: Custom Sorting Function.
  4. Method 4: Using a Priority Queue for Custom Sort Order.
Jun 3, 2024

How to check array of objects in TypeScript? ›

In TypeScript, checking if an array includes an object consists of comparing the object's properties within the array elements. We can compare and check this using three different approaches some method, find method, and includes method.

What is the type of array of objects in TypeScript? ›

In TypeScript, an array of objects is a data structure that allows us to store multiple objects in a single variable. Each object in the array can have multiple properties. An array of this kind is defined by using an interface to specify the structure of the objects.

How to do sorting of an array? ›

Steps
  1. Select the first element of the list.
  2. Compare the selected element with all other elements in the list.
  3. For every comparison, if any element is smaller (or larger) than selected element, swap these two elements.
  4. Repeat the same procedure with next position in the list till the entire list is sorted.

What is the fastest way to sort array? ›

In practice, Quick Sort is usually the fastest sorting algorithm. Its performance is measured most of the time in O(N × log N).

What is the formula for sort array? ›

The SORT function sorts the contents of a range or array. In this example, we're sorting by Region, Sales Rep, and Product individually with =SORT(A2:A17), copied across cells F2, H2, and J2.

How do you sort by column in TypeScript? ›

To enable sorting in the grid, set the allowSorting property to true. To sort a particular column in the grid, click on its column header. Each time you click the header, the order of the column will switch between Ascending and Descending. To use the sorting feature, you need to inject the Sort module in the grid.

How to get the return type in TypeScript? ›

Get the Return Type of an Async Function in Typescript

If we want to get the return type of our function, we need to use the Awaited utility: type SayHiReturnType = Awaited<ReturnType<typeof sayHi>>; Now SayHiReturnType has a value of string .

What is the return type of array sort? ›

The Arrays. sort() method has a return type of void, meaning it does not return an object/primitive, so you can't really assign the absent return value to a char[] . The array will be sorted through the reference to it (arrays are objects) passed to the method.

How do you sort an array of objects in TypeScript? ›

We can achieve the sorting in TypeScript using the sort() function which is an inbuilt TypeScript function that is used to sort the elements of an array. Below are a few examples showing the sorting in TypeScript.

How to iterate array of arrays in TypeScript? ›

You can use the forEach loop to iterate between the elements of an array, set, map, or list in TypeScript. We call the forEach method to iterate between the elements of an array. This function takes a callback function. You can perform operations on each array element within the callback function.

What are the types of sorting? ›

Some of the most common sorting algorithms are:
  • Selection sort.
  • Bubble sort.
  • Insertion sort.
  • Merge sort.
  • Quick sort.
  • Heap sort.
  • Counting sort.
  • Radix sort.
Dec 4, 2019

How do you sort an array of custom objects? ›

To sort an array of objects, use the sort() method with a compare function. A compareFunction applies rules to sort arrays by defined our own logic. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

How do you sort an object in an array list? ›

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.

How to filter an array of objects in TypeScript? ›

The 'filter()' Method in TypeScript

const newArray = array. filter(testFunction(element[, index[, array]])[, thisArg]); testFunction : The function used to test each element of the array. It should return true for elements that should be included in the new array.

How do you search in an array of objects in TypeScript? ›

The find() method in TypeScript searches the first element in the array, that satisfies the conditions of the testing function. If no element in the array satisfies the condition, the method returns undefined.

References

Top Articles
Debunking the Myth and Finding the Best Options – Rise.pizza
Frequently Asked Questions about Computer Help Desk
Ffxiv Act Plugin
Ohio Houses With Land for Sale - 1,591 Properties
Koopa Wrapper 1 Point 0
Coffman Memorial Union | U of M Bookstores
Davante Adams Wikipedia
Unraveling The Mystery: Does Breckie Hill Have A Boyfriend?
Category: Star Wars: Galaxy of Heroes | EA Forums
Ladyva Is She Married
Brutál jó vegán torta! – Kókusz-málna-csoki trió
FAQ: Pressure-Treated Wood
O'reilly's Auto Parts Closest To My Location
Dr Adj Redist Cadv Prin Amex Charge
The Ultimate Style Guide To Casual Dress Code For Women
Vintage Stock Edmond Ok
Ms Rabbit 305
Fsga Golf
Veracross Login Bishop Lynch
Never Give Up Quotes to Keep You Going
How many days until 12 December - Calendarr
Dcf Training Number
Craigslist Battle Ground Washington
Cain Toyota Vehicles
Southland Goldendoodles
Craigs List Jonesboro Ar
Kabob-House-Spokane Photos
8002905511
417-990-0201
Carespot Ocoee Photos
Page 5662 – Christianity Today
Mandy Rose - WWE News, Rumors, & Updates
Tirage Rapid Georgia
Dying Light Nexus
Review: T-Mobile's Unlimited 4G voor Thuis | Consumentenbond
B.C. lightkeepers' jobs in jeopardy as coast guard plans to automate 2 stations
Craigslist Pets Plattsburgh Ny
Registrar Lls
Best Restaurants Minocqua
Emily Tosta Butt
Subdomain Finder
Southwest Airlines Departures Atlanta
Goats For Sale On Craigslist
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
Craigslist Pet Phoenix
Cult Collectibles - True Crime, Cults, and Murderabilia
The Blackening Showtimes Near Ncg Cinema - Grand Blanc Trillium
The Machine 2023 Showtimes Near Roxy Lebanon
Mmastreams.com
Sams La Habra Gas Price
Craigslist Indpls Free
Texas 4A Baseball
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 6080

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.