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