How to sort an array of objects in typescript?

Viewed 49

I'm trying to sort by distance of an array of json. I've tried using the .sort() function but I'm unable to make it work. I'm coding in typescript.

sortArr = [
{id: 1, distance: 2.56},
{id: 2, distance: 3.65},
{id: 3, distance: 9.25},
{id: 4, distance: 5.32},
{id: 5, distance: 2.56}
]

sortArr.distance.sort(function(a,b){return a-b;});
3 Answers

You almost got it right:

sortArr = [
{id: 1, distance: 2.56},
{id: 2, distance: 3.65},
{id: 3, distance: 9.25},
{id: 4, distance: 5.32},
{id: 5, distance: 2.56}
]

sortArr.sort(function(a,b){return a.distance-b.distance;});

You need to call sort on your array:

const array = [
  {id: 1, distance: 2.56},
  {id: 2, distance: 3.65},
  {id: 3, distance: 9.25},
  {id: 4, distance: 5.32},
  {id: 5, distance: 2.56}
];

const sorted = array.sort((a, b) => a.distance - b.distance);
console.log(sorted);

Though, sortArr.distance.sort(function(a, b) { return a-b; }); should at least show one error:

Property 'distance' does not exist on type '{ id: number; distance: number; }[]'.
sortArr.sort(function(a,b){return a['distance']-b['distance'];});
Related