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)
Top Articles
Latest Posts
Article information

Author: Corie Satterfield

Last Updated:

Views: 6334

Rating: 4.1 / 5 (42 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Corie Satterfield

Birthday: 1992-08-19

Address: 850 Benjamin Bridge, Dickinsonchester, CO 68572-0542

Phone: +26813599986666

Job: Sales Manager

Hobby: Table tennis, Soapmaking, Flower arranging, amateur radio, Rock climbing, scrapbook, Horseback riding

Introduction: My name is Corie Satterfield, I am a fancy, perfect, spotless, quaint, fantastic, funny, lucky person who loves writing and wants to share my knowledge and understanding with you.