Sort array of objects in typescript [With 10 examples] - SPGuides (2024)

In this typescript tutorial, we will see how to sort an array of objects in typescript. We will cover different examples:

  • What is sorting an array of objects in typescript
  • typescript sort array of objects by value
  • typescript sort array of objects by string property
  • typescript sort array of objects by property alphabetically
  • typescript sort array of objects by number
  • typescript sort array of objects by name descending
  • typescript sort array of objects by name ascending
  • typescript sort array of objects by multiple properties
  • sort array of objects in typescript by date
  • typescript sort array of objects by boolean property

Table of Contents

What is sorting an array of objects in typescript?

In TypeScript, sorting an array of objects means arranging the array’s items in a certain order depending on the values of one or more attributes of the objects in the array.

For example, you may want to sort an array of Person objects in ascending or descending order by the age field, or alphabetically by the name property.

To sort an array of objects in TypeScript, use the sort() function, which is accessible on all arrays in Typescript. The sort() method accepts a comparison function as a parameter, which determines the order of the items in the sorted array.

If the first object comes before the second, the comparison function should return a negative number, a positive number if the second object comes before the first, and 0 if the order of the objects does not change.

Depending on the desired sort order, the comparison function can compare one or more characteristics of the items in the array.

The syntax of the sort method:

Array.sort(comparison function)

Typescript sort array of objects by value

Here we will see how to sort an array of objects by value with an example in typescript.

To sort an array of objects by a specific property value, we can use the sort() method in TypeScript with a custom comparison function that compares the values of that property for each object.

For example, we have an array of Candidate objects with two properties: name and age. We want to sort this array by the age property in ascending order in typescript.

For this, we will call the typescript sort() method on the candidate array and supply an argument of a custom comparison function.

This method in typescript compares the age properties of two Candidate objects, a and b, by subtracting b.age from a.age. If a.age is less than b.age, the outcome will be a negative number, a positive number if a.age is larger than b.age, and zero if they are equal.

Open the code editor, and create a file named as ‘ sortArrayOfObjects.ts’ file write the below code:

interface Candidate { name: string; age: number; } const person: Candidate[] = [ { name: "John", age: 43 }, { name: "Alex", age: 39 }, { name: "Bob", age: 33 } ]; person.sort((a, b) => a.age - b.age); console.log(person);

To compile the code and run the below command and you can see the result in the console:

ts-node sortArrayOfObjects.ts
Sort array of objects in typescript [With 10 examples] - SPGuides (1)

This is an example of a typescript sort array of objects by value.

Read How to convert a string to boolean in typescript

Typescript sort array of objects by string property

Here we will see an example of how to sort an array of objects by string property in typescript.

See also as Keyword in Typescript

For example, we have an array of Candidate objects with two properties: name and age. We want to sort this array by the typescript name property in ascending order.

For this, we will call the typescript sort() method on the candidate array and supply an argument of a custom comparison function.

This method in typescript compares the name properties of two Candidate objects, a and b, by subtracting b.name from a.name. If a.name is less than b.name, the outcome will be a negative number, a positive number if a.name is larger than b.name, and zero if they are equal.

In the sortArrayOfObjects.ts file write the below code

interface Candidate { name: string; age: number; } const person: Candidate[] = [ { name: "John", age: 43 }, { name: "Alex", age: 39 }, { name: "Bob", age: 33 } ]; person.sort((a, b) => a.name.localeCompare(b.name)); console.log(person);

To compile the code and run the below command and you can see the result in the console:

ts-node sortArrayOfObjects.ts
Sort array of objects in typescript [With 10 examples] - SPGuides (2)

This is an example of a Typescript sort array of objects by string property.

Typescript sort array of objects by property alphabetically

Here we will see an example to sort an array of objects by property alphabetically in typescript.

For example, to sort an array of objects alphabetically by a property in TypeScript, you can use the sort() method of the Array object along with a comparison function.

For example, we have an array of objects Candidate that has a name property. We use the sort() method to sort the array, and we pass in a comparison function that compares the name property of two objects. The function returns 1 if a.name is greater than b.name, and -1 if a.name is less than b.name. This will sort the array in ascending order based on the name property.

In the sortArrayOfObjects.ts file write the below code:

interface Candidate { name: string; age: number; } const person: Candidate[] = [ { name: "John", age: 43 }, { name: "Alex", age: 39 }, { name: "Bob", age: 33 } ]; person.sort((a, b) => (a.name > b.name) ? 1 : -1) console.log(person);

To compile the code and run the below command, you can see the result in the console:

ts-node sortArrayOfObjects
Sort array of objects in typescript [With 10 examples] - SPGuides (3)

This is an example of a typescript sort array of objects by property alphabetically.

Typescript sort array of objects by number

Here we will see an example of how we can sort an array of objects by number.

To sort an array of objects by a numeric property in TypeScript, we can use the Array.sort() method in combination with the localeCompare() function to compare the string representations of the numeric values.

For example, we have an array of Candidate objects with two properties: name and age. We want to sort this array by the typescript age property in ascending order.

For this, we will call the typescript sort() method on the candidate array and supply an argument of a custom comparison function.

This method in typescript compares the age properties of two Candidate objects, a and b, by subtracting b.age from a.age. If a.age is less than b.name, the outcome will be a negative number, a positive number if a.age is larger than b.age, and zero if they are equal.

In the sortArrayOfObjects.ts file write the below code:

interface Candidate { name: string; age: number; } const person: Candidate[] = [ { name: "John", age: 43 }, { name: "Alex", age: 39 }, { name: "Bob", age: 33 } ]; person.sort((a, b) => a.age.toString().localeCompare(b.age.toString())) console.log(person);

To compile the code and run the below command and you can see the result in the console:

ts-node sortArrayOfObjects.ts
Sort array of objects in typescript [With 10 examples] - SPGuides (4)

This is an example of typescript sort array of objects by number.

See also TypeScript Split String Into Array

Read How to check if string contains only numbers in typescript

Typescript sort array of objects by name descending

Here we will see an example of how to sort an array of objects by name descending in typescript.

To sort an array of objects by name in descending order using TypeScript, you can use the Array.sort() method in combination with a custom comparator function that compares the string values of the name property.

For example, we have an array of objects with two properties: age and name. We want to sort the array by the name property in descending order.

We will use the typescript Array.sort() method, which accepts a comparator function and compares two values, returning a negative number if the first value comes before the second, a positive number if the first comes after the second, or zero if they are equal.

To compare the name property of object b with that of object a, we use the string object’s localeCompare() function. If the result is negative, b should come before a; if the result is positive, b should come after aand if the result is zero, they are equal and their order remains unchanged.

After using person. sort() the array is sorted in decreasing order by the name property after using person.sort().

In the sortArrayOfObjects.ts file, write the below code:

 interface Candidate { name: string; age: number; } const person: Candidate[] = [ { name: "John", age: 43 }, { name: "Alex", age: 32 }, { name: "Bob", age: 33 } ]; person.sort((a, b) => b.name.localeCompare(a.name)) console.log(person);

To compile the code and run the below command and you can see the result in the console.

ts-node sortArrayOfObjects.ts
Sort array of objects in typescript [With 10 examples] - SPGuides (5)

This is an example of Typescript sort array of objects by name descending

Typescript sort array of objects by multiple properties

Here we will see how to sort an array of objects by multiple properties using typescript.

To sort an array of objects by multiple properties in TypeScript, you can use the Array.sort() method in combination with a custom comparator function that compares the values of the properties in the desired order.

In this example, we have an array of objects with three properties: id, name, and age. We want to sort the array by the age property in ascending order and then by the name property in descending order in typescript.

We will create a comparator function first compares the age properties of the two objects. If they are not equal, it returns the difference between the age values, which will result in sorting by age in ascending order in the typescript.

If the age values are equal, it then compares the name properties of the two objects using localeCompare() in reverse order, which will result in sorting by name in descending order.

By calling person.sort(), the array is sorted by age in ascending order, and then by name in descending order.

In the sortArrayOfObjects.ts file, write the below code:

interface Candidate { id: number name: string; age: number; } const person: Candidate[] = [ { id:1,name: "John", age: 43 }, {id:3, name: "Alex", age: 32 }, { id:5,name: "Ron", age: 33 }, { id:5,name: "Ketty", age: 40 }, { id:5,name: "Rose", age: 39 } ]; person.sort((a, b) => { if (a.age !== b.age) { return a.age - b.age; } else { return b.name.localeCompare(a.name); } }) console.log(person);

To compile the code and run the below command and you can see the result in the console.

ts-node sortArrayOfObjects.ts
Sort array of objects in typescript [With 10 examples] - SPGuides (6)

This is an example of a sort array of objects by multiple properties in typescript.

Read Typescript convert string to keyof

Sort array of objects in typescript by date

Here we will see an example to sort an array of objects in typescript by date.

See also How to Declare a Dictionary in TypeScript?

For example, we have an array of objects with three properties: id, name, age and date. We want to sort the array by the date property in ascending order.

The comparator function accepts two parameters and returns a negative number if the first object’s date is earlier than the second object’s date, a positive number if the first object’s date is later than the second object’s date, and zero if they are equal.

We can compare the dates by using the Date object’s getTime() function, which provides the number of milliseconds since January 1, 1970 00:00:00 UTC. We may sort by date in ascending order by subtracting the getTime() values of the two objects.

In the sortArrayOfObjects.ts file, write the below code:

interface Candidate { id: number name: string; age: number; date:Date } const person: Candidate[] = [ { id:1,name: "John", age: 43, date: new Date('2022-01-01') }, {id:3, name: "Alex", age: 32, date: new Date('2022-02-01') }, { id:5,name: "Ron", age: 33, date: new Date('2022-03-01') }, { id:5,name: "Ketty", age: 40, date: new Date('2022-05-01') }, { id:5,name: "Rose", age: 39, date: new Date('2022-06-07') } ]; person.sort((a, b) => a.date.getTime() - b.date.getTime()) console.log(person);

To compile the code and run the below command and you can see the result in the console:

ts-node sortArrayOfObjects.ts
Sort array of objects in typescript [With 10 examples] - SPGuides (7)

This is an example of Sort array of objects in typescript by date.

Read How to push an object into an array in Typescript

typescript sort array of objects by boolean property

Here we will see how to sort an array of objects by boolean property in typescript.

For example, we have an array of objects with three properties: id, name, and isComplete. We want to sort the array by the isComplete property in descending order.

Here, The comparator function takes two objects as arguments and returns a negative number if the first object’s isComplete value is true and the second object’s isComplete value is false, a positive number.

If the first object’s isComplete value is false and the second object’s isComplete value is true, or zero if they are equal. We can achieve this by using a ternary operator to return 1 or -1 depending on the isComplete value of the two objects.s.

In the sortArrayOfObjects.ts file, write the below code:

 interface Task { id: number; name: string; isComplete: boolean; } const tasks: Task[] = [ { id: 1, name: 'Task 1', isComplete: false }, { id: 2, name: 'Task 2', isComplete: true }, { id: 3, name: 'Task 3', isComplete: true }, { id: 4, name: 'Task 4', isComplete: false } ]; tasks.sort((a, b) => b.isComplete ? 1 : -1); console.log(tasks);

To compile the code and run the below command and you can see the result in the console:

ts-node sortArrayOfObjects.ts
Sort array of objects in typescript [With 10 examples] - SPGuides (8)

This is an example of typescript sort array of objects by boolean property.

Conclusion

In this typescript tutorial, we saw how to sort an array of objects in typescript. Also, we have gone through different examples to sort an array of objects:

  • What is sorting an array of objects in typescript
  • typescript sort array of objects by value
  • typescript sort array of objects by string property
  • typescript sort array of objects by property alphabetically
  • typescript sort array of objects by number
  • typescript sort array of objects by name descending
  • typescript sort array of objects by name ascending
  • typescript sort array of objects by multiple properties
  • sort array of objects in typescript by date
  • typescript sort array of objects by boolean property

You may like the following typescript tutorials:

  • Typescript string capitalize first letter
  • Typescript split string by dot
  • How to create a multiline string in typescript
  • How to split a string with multiple separators in TypeScript?

Sort array of objects in typescript [With 10 examples] - SPGuides (9)

Bijay Kumar

I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com

Sort array of objects in typescript [With 10 examples] - SPGuides (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 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.

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

To sort an array in TypeScript we could use Array. sort() function. The Array. sort() is an inbuilt TypeScript function that is used to sort the elements of an array.

How do you sort an array of items? ›

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.

How to sort array of array of objects in JavaScript? ›

  1. function sortDataBy (data, byKey){ //here your logic code }
  2. let sortedData;
  3. if(byKey == 'name'){ //your logic for name } else if(byKey == 'age'){ //your logic for age }
  4. // we use javascript sort function to compare to value sortedData = data. ...
  5. sortedData = data. ...
  6. return sortedData;
  7. console.
Mar 25, 2021

What is an 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 do you find 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.

How to check array has elements in TypeScript? ›

The includes() method determines whether an array contains a specified element. This method returns true if the array contains the element, and false if not.

What is the difference between array and object in TypeScript? ›

Arrays are used when we need to collection a list of elements of the same data type or structure. On the other hand, objects are used when grouping multiple sets of data that belong together using labels, where each property or key has its own value of any type.

How do you sort an array of objects by string? ›

Approach 1: Using sort() with a custom compare function

In this approach, sort() is used with a custom compare function that utilizes localeCompare() to sort the array of objects by a string property value. Example: In this example, we are using the above-explained approach.

How do you sort by column in TypeScript? ›

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. Grid column sorted in Ascending order.

How do you sort an array list of arrays? ›

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.

How to sort an array of objects by a property value in Typescript? ›

const sortedArray = sortBy(array, [propertyName]); array: The array of objects to be sorted. propertyName: The property of the objects by which to sort.

What is the easiest way to sort an array? ›

Bubble Sort

This is the simplest sorting algorithm. We'll compare each adjacent pair and check if the elements are in order. If they aren't, we swap both elements. We keep doing this until all elements are sorted.

How do you directly sort an array? ›

For sorting an array of numbers, the comparison function should subtract the second number from the first number. This will result in a negative number if the first number is smaller than the second number, a positive number if the first number is larger than the second number, and 0 if the two numbers are equal.

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 do you 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 an object array 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.

Top Articles
Latest Posts
Article information

Author: Geoffrey Lueilwitz

Last Updated:

Views: 5572

Rating: 5 / 5 (60 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Geoffrey Lueilwitz

Birthday: 1997-03-23

Address: 74183 Thomas Course, Port Micheal, OK 55446-1529

Phone: +13408645881558

Job: Global Representative

Hobby: Sailing, Vehicle restoration, Rowing, Ghost hunting, Scrapbooking, Rugby, Board sports

Introduction: My name is Geoffrey Lueilwitz, I am a zealous, encouraging, sparkling, enchanting, graceful, faithful, nice person who loves writing and wants to share my knowledge and understanding with you.