1

am trying to sort xy coordinates on both sub index it once mean row column Asc order. i have sorted coordinates data via Y but when i sort that data again via X then i lost Y order , so any idea how to do it?

what i have done

example: my raw coordinates xy data

var cxray = [ [450,13],[455,12],[454,12],[451,12],[452,13],[453,12], [450,12],[453,13],[454,13],[450,13],[452,12],[455,13],];

my single index sorting function

 this.ray_isort = function(data,i){
    data.sort( function( a, b ,sindex=i){if ( parseFloat(a[sindex]) == parseFloat(b[sindex]) ) return 0;return parseFloat(a[sindex]) < parseFloat(b[sindex]) ? -1 : 1;});
    return data;
  };

Fiddle Link : JSFIDDLE

currently when i sort it with one index i get output

0  451,12
1  454,12
2  450,12
3  453,12
4  455,12
5  452,12
6  452,13
7  453,13
8  454,13
9  450,13
10  450,13
11  455,13

my goal is to get

0  450,12
1  451,12
2  452,12
3  453,12
4  454,12
5  455,12
6  450,13
7  451,13
8  452,13
9  453,13
10  454,13
11  455,13
1
  • array.sort((a,b)=> a[0]-b[0] || a[1] - b[1]) Commented Jul 14, 2017 at 11:28

2 Answers 2

3

a[1] - b[1] will sort the array using the second items of each array.

If they're equal, the result will be 0 and thus the a[0] - b[0] part will be executed and will sort the array using the first items.

const cxray = [ [450,13],[455,12],[454,12],[451,12],[452,13],[453,12], [450,12],[453,13],[454,13],[450,13],[452,12],[455,13],];

console.log(cxray.sort((a, b) => a[1] - b[1] || a[0] - b[0]));

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

1 Comment

Please add explanation as you are answering for readers and not just OP
1
cxray.sort(([ax,ay],[bx,by])=>ay-by||ax-bx);

Simply sort after y first. If ay equals by, ay-by will be 0, so thanks to the or operator it will be then sorted after x.

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.