coolguy
coolguy

Reputation: 7954

JavaScript object array not properly sorting

I have this object array

var grps = [{
    group_no: 0,
    id: "733",
    xpos: 226.72,
    ypos: 100
}, {
    group_no: 0,
    id: "735",
    xpos: -1.19,
    ypos: 200
}];

and im trying to sort the array based on value xpos

var small_x = grps.sort(function(a, b) {
    return a.xpos - b.xpos;
});

and when i do

 console.log(small_x[0].xpos); //sort asc

I expect the value to be -1.19 but iam getting 226.72

Upvotes: 0

Views: 1970

Answers (1)

schellingerht
schellingerht

Reputation: 5796

See below (works also for string values). The ECMA script doesn't specify which algoritm has been used. But, simply said, compare posx of a is <, > or (else) == posx of b. This returns resp. -1, 1 or 0, which could be sort simply.

See also the documentation of Mozilla Developer Network with description, examples, ECMA script notes, and the example below (conceptual): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

function comparePos(a, b)
{
   if (a.xpos < b.xpos)
      return -1;
   if (a.xpos > b.xpos)
      return 1;
   return 0;
}

grps.sort(comparePos);

See this: Sort array of objects by string property value in JavaScript

Upvotes: 2

Related Questions