Sorting elements in an Array

Hello Folks,
I’m trying to sort an array row-wise. The array contains coordinate points (x, y). I tried to sort the array but I am not getting the expected result. Any help will be highly appreciated.
Link to my notebook: Sorting elements in an Array / JS | Observable

Expected outcome

``````SortedArray =  Array(2) [
0: Array(3)
[0: Object{x: 56.71095406360424, y: 60.00740978691508}
1:  Object {x: 173, y: 52.6015625}
2: Object {x: 306, y: 49.6015625}
]
1: Array(3) [
0: Object {x: 50.02022114840451, y: 194.40599016150796}
1: Object {x: 176.21168146293346, y: 186.11935655209044}
2: Object {x: 296.82501974946393, y: 182.13051574314412}
]
]
``````

Thanks a lot!

Try the following:

``````ExampleArray.sort((a, b) => a.y - b.y || a.x - b.x)
``````
1 Like

@mootari Thanks a lot! It worked but still has some issues. Indexes are not correct order. Find my output below.

``````SortedArray = Array(2) [
0:  Array(3) [
0: Object {x: 306, y: 49.6015625}
1:  Object {x: 173, y: 52.6015625}
2: Object {x: 56.71095406360424, y: 60.00740978691508}
]
1: Array(3) [
0: Object {x: 296.82501974946393, y: 182.13051574314412}
1: Object {x: 176.21168146293346, y: 186.11935655209044}
2: Object {x: 50.02022114840451, y: 194.40599016150796}
]
]
``````

Seems I forgot to swap x and y. I’ll leave that as an exercise to you.

If I swap x and y, `points_array.sort((a, b) => a.x - b.x || a.y - b.y)`, I am getting something like below, but this is not the result I’m expecting. BTW thanks a lot for your suggestions. I’m trying to tweak it a little bit.

``````SortedArray = Array(2) [
0:  Array(3) [
0: Object {x: 50.02022114840451, y: 194.40599016150796}
]
1:  Object {x: 56.71095406360424, y: 60.00740978691508}
2: Object {x: 173, y: 52.6015625}
]
1: Array(3) [
0: Object {x: 176.21168146293346, y: 186.11935655209044}
1: Object {x: 296.82501974946393, y: 182.13051574314412}
2: Object  {x: 306, y: 49.6015625}
]
``````

Your array slicing aside, the order looks correct to me. I’m not sure what result you expect.

If I swap x and y, mostly points are sorted based on x or y, but I am expecting result should be like this (if I don’t apply slicing).

``````Array[6] [
0: Object {x: 56.71095406360424, y: 60.00740978691508}
1: Object {x: 173, y: 52.6015625}
2: Object {x: 306, y: 49.6015625}
3: Object {x: 50.02022114840451, y: 194.40599016150796}
4: Object {x: 176.21168146293346, y: 186.11935655209044}
5: Object {x: 296.82501974946393, y: 182.13051574314412}
]
``````

We already discussed the topic at length in Organize centroid points into Array Structure - #6 by mootari where I even gave a solution for this sort of binning. Why have you created this new topic?

1 Like

That partially solved my issue. After slicing, the array index for the second row is just reversed. So, I am thinking about a better solution.

@mootari Thanks a lot! Your code helped me to solve my issue. Thanks a lot once again!