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

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 property
let sortedAscendingCountries = countries.sort(function (first, second) {
  return first.id - second.id;
});

console.log(sortedAscendingCountries);

// Sorted by descending id property
let sortedDescendingCountries = countries.sort(function (first, second) {
  return second.id - first.id;
});

console.log(sortedDescendingCountries);

Output:

[
  { id: 1, name: "USA" },
  { id: 3, name: "Canada" },
  { id: 21, name: "India" },
][
  ({ id: 21, name: "India" }, { id: 3, name: "Canada" }, { id: 1, name: "USA" })
];

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.