1

I have a two dimensional array where the first is the distance and second is the object:

[distance][object]

I need to order by distance - I'm trying something like this but it doesn`t work, someone could help me?

lista.sort((a, b) => {return a-b});

and

let t = lista.sort(sortFunction);

sortFunction(a, b) {
    if (a[0] === b[0]) {
        return 0;
    }
    else {
        return (a[0] < b[0]) ? -1 : 1;
    }
}
1
  • 3
    Can you please provide some real sample input and output? Commented Nov 7, 2018 at 22:36

1 Answer 1

2

If I understand your question correctly, the the following should work for you - the idea here is to call .sort() on the "outer array" of your two-dimensional dataset, and pass a comparison function that tests the first element (ie the distance data) of each item being compared:

var data = [
  [22, { object : 22 }],
  [10, { object : 10 }],
  [3, { object : 3 }],
  [50, { object : 50 }]
]

console.log('unsorted:', data)

data.sort((a, b) => {
  return a[0] - b[0]
})

console.log('sorted:', data)

Sign up to request clarification or add additional context in comments.

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.