0

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

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
coolguy
  • 7,866
  • 9
  • 45
  • 71
  • Seems works fine http://jsfiddle.net/5pbkddgo/ – Oleksandr T. Aug 04 '15 at 05:54
  • http://jsfiddle.net/arunpjohny/cz7sasct/ - looks fine – Arun P Johny Aug 04 '15 at 05:55
  • @ArunPJohny is there any way it is not sorting correctly because of string – coolguy Aug 04 '15 at 06:33
  • @coolguy—the *xpos* property is a number, so strings aren't your issue. Even if the values are strings like `'-1.19'` it will still work OK as the `-` operator coerces the operands to Number anyway (e.g. you can sort by *id* too even though the values are strings like `"735"`). – RobG Aug 04 '15 at 06:41
  • 1
    @coolguy yes... if it is doing a string comparison try http://jsfiddle.net/arunpjohny/cz7sasct/3/ – Arun P Johny Aug 04 '15 at 06:42

1 Answers1

2

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

Community
  • 1
  • 1
schellingerht
  • 5,726
  • 2
  • 28
  • 56