How to Sort-Object Array by property or key in Typescript? (2024)

In this tutorial, you will learn how to effectively sort object arrays by keys or properties in TypeScript.

An object holds the key and value of a real entity, and an object array is essentially a list of such objects.

There are several methods to sort object arrays, including:

  • Using ES5
  • Utilizing ES6/ES2015 syntax
  • Employing lodash’s sortBy function
  • Leveraging UnderscoreJS’s sortBy function
  • Implementing Ramda’s sortBy function
  • TypeScript/Javascript Array provides a sort method that takes a function callback.

Typescript/Javascript Array provides a sort method that takes function callback.

#Using sort Method

sort(function (first, second) { return first.property - second.property;});

Here, the function returns values by subtraction:

If the result is negative, the first number comes before the second. If positive, the second number comes before the first. If zero, both numbers are considered equal.

#ES6 way sorting Array of an object by key property

Let’s sort an array of objects by the key property in both ascending and descending orders.

var countries = [ { id: 1, name: "USA" }, { id: 21, name: "India" }, { id: 3, name: "Canada" },];// Sorted by ascending id propertylet sortedAscendingCountries = countries.sort(function (first, second) { return first.id - second.id;});console.log(sortedAscendingCountries);// Sorted by descending id propertylet sortedDescendingCountries = countries.sort(function (first, second) { return second.id - first.id;});console.log(sortedDescendingCountries);

Output:

#Sorting Array of Objects with Comparison Logic (ES6/ES2015)

Let’s declare an array of objects, each containing id and name properties, and sort it in ascending order based on the id property:

The sort method provided a lambda expression that has no name.

var countries = [ { id: 1, name: "USA" }, { id: 2, name: "India" }, { id: 3, name: "Canada" },];let sortedCountries = countries.sort( (first, second) => 0 - (first.id > second.id ? -1 : 1),);console.log(sortedCountries);

And the output:

[ { "id": 1, "name": "Canada" }, { "id": 18, "name": "USA" }, { "id": 21, "name": "India" }]

here is an example array object ordered in descending.

let descendingCountries = countries.sort( (first, second) => 0 - (first.id > second.id ? 1 : -1),);

Here is the output

[ { id: 21, name: "India" }, { id: 18, name: "USA" }, { id: 1, name: "Canada" },];

#Utilizing lodash’s sortBy Function

Lodash library offers various utility functions, including sortBy for sorting arrays.

First, install lodash npm or include lodash CDN library into your application.

syntax

sortBy(array or objects,[iteratekeys])

Input is an array of objects. iteratekeys are keys or properties that enable to sort

It returns a sorted array

Following is an example for sorting objects with key values of an object array in ascending order.

  • import all utilities using the import keyword
  • an animal object has key-id, name, and values
  • Declared animals array initialized with an animal object
  • sortBy in lodash method takes an object array with keys
  • Returns a sorted object array in id/name ascending order
import * as _ from "underscore";varanimals = [ { id: 11, name: "Zebra" }, { id: 2, name: "Elephant" }, { id: 3, name: "Cat" },];_.sortBy(animals, ["name"]); // sort by key name_.sortBy(animals, ["id"]); // sort by key id

And the output is

[Object {id: 3, name: "Cat"}, Object {id: 2, name: "Elephant"}, Object {id: 1, name: "Zebra"}][Object {id: 2, name: "Elephant"}, Object {id: 3, name: "Cat"}, Object {id: 11, name: "Zebra"}]

Following an example for sort object array with multiple fields

sortBy second arguments accept iterate keys, please give multiple keys.

_.sortBy(animals, ["id", "name"]);_.sortBy(animals, ["name", "id"]);

The first property is considered, if there is the same value for the first property, then sort these same values on a second property, please see the difference.

And the output is

[Object {id: 2, name: "Elephant"}, Object {id: 3, name: "Cat"}, Object {id: 11, name: "Zebra"}][Object {id: 3, name: "Cat"}, Object {id: 2, name: "Elephant"}, Object {id: 11, name: "Zebra"}]

#Sorting by Date Property Using Underscore

Underscore, like lodash, offers various utility functions.

Thesort by function in the underscore provides sorting of an array of objects with multiple attributes. The syntax and usage are the same as Lodash sortBy.

In the following example, An object contains properties with creating contains date and time. This sort is based on created date.

var employees = [ { id: 18, name: "Johh", created: "2020-08-1 07:12:10.0" }, { id: 21, name: "Frank", created: "2019-08-1 07:12:10.0" }, { id: 1, name: "Eric", created: "2018-08-1 07:12:10.0" },];_.sortBy(employees, ["created"]);

And the output is

0: Object {created: "2018-08-1 07:12:10.0", id: 1, name: "Eric"}1: Object {created: "2019-08-1 07:12:10.0", id: 21, name: "Frank"}2: Object {created: "2020-08-1 07:12:10.0", id: 18, name: "Johh"}

#Sorting by Property Using Ramda

Ramda also provides a sortBy function for sorting arrays:

import R from "ramda";var employees = [ { id: 18, name: "Johh", created: "2020-08-1 07:12:10.0" }, { id: 21, name: "Frank", created: "2019-08-1 07:12:10.0" }, { id: 1, name: "Eric", created: "2018-08-1 07:12:10.0" },];var employeesInCreatedAscendingOrder = R.sortBy(R.prop("created"), employees);

#Conclusion

In this blog post, you learned multiple ways to effectively sort object arrays:

  • Comparison of object fields with keys using ES5 and ES6 lambda expressions
  • Sorting an array of objects with multiple properties using lodash
  • Sorting by object date values with Underscore
  • Utilizing Ramda’s sortBy function for sorting by property.
How to Sort-Object Array by property or key in Typescript? (2024)

FAQs

How to Sort-Object Array by property or key 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 sort an array of objects based on a property value in JavaScript? ›

To sort an array of objects by a specific key (property) in JavaScript, you can use the Array. prototype. sort() method along with a custom comparison function that compares the values of the desired key for each object.

How to get keys of array in TypeScript? ›

TypeScript keys() method is not directly available on arrays. Instead, you can use the keys() method from the Object class to get the keys of an array. When applied to an array, Object. keys() returns an array containing the string representations of the indices.

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 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 do you sort objects by property 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 filter array of objects by key? ›

Filter object properties by key

entries() to get an array of the object's key-value pairs, then use Array. prototype. filter() to filter the key-value pairs based on the provided array.

How to write array of object in TypeScript? ›

Syntax: const array_name: Array<{key1: type1, key2: type2, key3: type3}> = [{}]; Example: This example will show you the use of the Array type to create an array of object in TypeScript.

How to get object array by property in JavaScript? ›

To access properties inside an array of objects in JavaScript, you can use the array method forEach() or map() . Then, you can use an if...else statement to perform different actions based on the value of the property.

How to sort an array of objects by date property in JavaScript? ›

To sort an object array by date using `Intl. DateTimeFormat` and `Array. prototype. sort()`, convert the date strings to formatted dates, then use the `sort` method with a custom compare function that compares the formatted dates.

How to get object by key in TypeScript? ›

In TypeScript, you can use the Object. keys() method to get an array of the object's own enumerable property names. Then, you can iterate over this array to find and access the value associated with a specific key.

How to get the keys of each object in an array? ›

The Object.

keys() method in JavaScript allows you to get an array of all the keys of a given object. The JS feature is designed to loop over all the properties of an object because it is a simple way to access and manipulate each key individually.

How to get object array keys in JavaScript? ›

Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object . This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well.

How to find the key in an array of objects in TypeScript? ›

To get a particular key value from an array of objects in TypeScript, you can use array methods like find() or filter() along with arrow functions to search for the object with the desired key value.

How do you access array elements in TypeScript? ›

Accessing Array Elements:

The array elements can be accessed using the index of an element e.g. ArrayName[index] . The array index starts from zero, so the index of the first element is zero, the index of the second element is one and so on. Use the for loop to access array elements as shown below.

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

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

In TypeScript, while working with the array, we often require to search for a particular element. To search for an element, either we can use the naive approach using the for loop or some built-in method such as the find() or indexOf() method.

How to check an array in TypeScript? ›

The Array. find() method can be utilized with a boolean condition to check if an array contains a specific string. This approach returns the found string if it exists in the array, otherwise returns undefined.

How to sort the array of JSON object based on specific key name? ›

Using sort() Function

In this approach, we are using the sort() function in JavaScript to sort a JSON object array (jData) based on the 'name' key. The sorting is done by comparing the 'name' values of each object using a comparator function within the sort() method.

Does object keys work on array? ›

Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object . This is the same as iterating with a for...in loop, except that a for...in loop enumerates properties in the prototype chain as well.

How do you check if an array of objects contains a specific key? ›

You can use the in-operator or the hasOwnProperty() method to check if a key is in a JavaScript object or array. The in operator tells you if the key is there, and the hasOwnProperty() method shows if the key is a direct property of the object.

How to sort array of objects JavaScript by boolean key? ›

JavaScript arrays have a built-in sort() method that allows for custom sorting logic via a comparator function. When sorting by a boolean property, this function can simply return the difference between the boolean values of two objects.

Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 5574

Rating: 4 / 5 (61 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.