Sort an array of objects in typescript? Sort an array of objects in typescript? angular angular

Sort an array of objects in typescript?


It depends on what you want to sort. You have standard sort funtion for Arrays in JavaScript and you can write complex conditions dedicated for your objects. f.e

var sortedArray: Test[] = unsortedArray.sort((obj1, obj2) => {    if (obj1.cognome > obj2.cognome) {        return 1;    }    if (obj1.cognome < obj2.cognome) {        return -1;    }    return 0;});


Simplest way for me is this:

Ascending:

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

Descending:

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

In your case,Ascending:

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

Descending:

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


    const sorted = unsortedArray.sort((t1, t2) => {      const name1 = t1.name.toLowerCase();      const name2 = t2.name.toLowerCase();      if (name1 > name2) { return 1; }      if (name1 < name2) { return -1; }      return 0;    });