iAmRed
iAmRed

Reputation: 83

How to sort an array of objects in typescript?

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;});

Upvotes: 2

Views: 95

Answers (3)

shalini
shalini

Reputation: 1290

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

Upvotes: 1

pzaenger
pzaenger

Reputation: 11973

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; }[]'.

Upvotes: 3

Łukasz Karczewski
Łukasz Karczewski

Reputation: 1208

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;});

Upvotes: 4

Related Questions