How do I sort an array of objects by attribute in TypeScript?

How do I sort an array of objects in TypeScript? Specifically, I want to sort the objects based on one specific attribute, such as nome (“name”) or cognome (“surname”).

Here is the relevant code:

/* Object Class */ export class Test { nome: string; cognome: string; }

/* Generic Component.ts */ tests: Test[]; test1: Test; test2: Test;

this.test1.nome = ‘Andrea’; this.test2.nome = ‘Marizo’; this.test1.cognome = ‘Rossi’; this.test2.cognome = ‘Verdi’;

this.tests.push(this.test2); this.tests.push(this.test1);

How can I sort this.tests based on the nome or cognome attribute using typescript sort array of objects? Thanks!

The simplest way to sort an array of objects in TypeScript is as follows:

Ascending Order: arrayOfObjects.sort((a, b) => (a.propertyToSortBy < b.propertyToSortBy ? -1 : 1));

Descending Order: arrayOfObjects.sort((a, b) => (a.propertyToSortBy > b.propertyToSortBy ? -1 : 1));

In your case, to sort tests by nome or cognome:

Ascending Order:

testsSortedByNome = tests.sort((a, b) => (a.nome < b.nome ? -1 : 1));
testsSortedByCognome = tests.sort((a, b) => (a.cognome < b.cognome ? -1 : 1));

Descending Order:

testsSortedByNome = tests.sort((a, b) => (a.nome > b.nome ? -1 : 1));
testsSortedByCognome = tests.sort((a, b) => (a.cognome > b.cognome ? -1 : 1));

You can use the following method to sort an array of objects:

let sortedArray: Array<ModelItem>;
sortedArray = unsortedArray.slice(0);
sortedArray.sort((left, right) => {
    if (left.id < right.id) return -1;
    if (left.id > right.id) return 1;
    return 0;
});

This approach creates a copy of the unsortedArray and sorts it based on the id attribute.

To enhance readability and reusability, you can create a helper function like this:

export const by = <T>(attribute: keyof T) => {
  return (one: T, two: T) => {
    if (one[attribute] < two[attribute]) {
      return -1;
    } else if (one[attribute] > two[attribute]) {
      return 1;
    } else {
      return 0;
    }
  };
};

Then, use this helper function to sort an array:

const users = [ /* items here */ ];
const sorted = users.sort(by('name'));