2

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;});
1
  • 1
    "array of json", no. that is an array of objects. json is a serialized data format and is always a string. Commented Jan 31, 2021 at 15:32

3 Answers 3

4

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;});
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.