1

I have an array of objects like this:

[ {x: 1, y: 4}, {x: 1, y: 2}, {x: 1, y: 3},
  {x: 3, y: 4}, {x: 3, y: 2}, {x: 3, y: 9},
  {x: 2, y: 5}, {x: 1, y: 0}, {x: 1, y: 2} ]

and I'd like to sort it like this:

[ {x: 1, y: 2}, {x: 1, y: 3}, {x: 1, y: 4},
  {x: 2, y: 0}, {x: 2, y: 2}, {x: 2, y: 5},
  {x: 3, y: 2}, {x: 3, y: 4}, {x: 3, y: 9} ]

so the rule is: the array has to be sorted first by the x property, and then the sorting by the y property has to observe the first sorting.

How can I do that?

I tried:

array.sort(function(a, b){
 var elema = a["x"] ;
 var elemb = b["x"] ;
 if (elema < elemb) 
  return -1;
 if (elema > elemb)
  return 1;
 return 0;
});

array.sort(function(a, b){
 var elema = a["y"] ;
 var elemb = b["y"] ;
 if (elema < elemb) 
  return -1;
 if (elema > elemb)
  return 1;
 return 0;
});

but it does not work properly.

Thanks

2 Answers 2

3

You have to do it in one function.
Also, if x values are the same, you must compare on y values.

You can do it this way

function SortMyObjects(a, b) 
{
   if (a.x < b.x)
      return -1;

   if (a.x > b.x)
      return 1;

   // a.x == b.x so compare y values
   if (a.y < b.y)
      return -1;

   if (a.y > b.y)
      return 1;

   // perfect equality
   return 0;
}

// sort your array
array.sort(SortMyObjects);
Sign up to request clarification or add additional context in comments.

Comments

0

You can do it in one line with Alasql JavaScript library. This is an example:

var res = alasql('SELECT * FROM ? ORDER BY x,y',[data]);

Try this example at jsFiddle.

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.