Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of items (with X/Y properties) so they are ordered left to right, top to bottom

Each item in the array in on the stage, each with an x/y position. The item in the top left most position should be items[0]. X should be the primary.

enter image description here

Originally I was thinking along the lines of:

var items = [m1, m2, m3, m4, m5, m6];

items.sort(sortMe);    

function sortMe(a, b)
{
    return (b.position[0] - a.position[0]) && (b.position[1] - a.position[1]);
}

But this does not yield the correct results.

like image 862
Chris Avatar asked Sep 17 '25 09:09

Chris


1 Answers

sort() should return either 0 or a negative/positive number.

This sorts with X taking precedence:

function sortByPosition(a, b){
  if (a.x == b.x) return a.y - b.y;
  return a.x - b.x;
}

This with Y taking precedence (the "natural" order):

function sortByPosition(a, b){
  if (a.y == b.y) return a.x - b.x;
  return a.y - b.y;
}

Which means you just need to replace your && with ||:

return a.x - b.x || a.y - b.y
like image 125
Ricardo Tomasi Avatar answered Sep 20 '25 01:09

Ricardo Tomasi