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

5
  • Seems works fine jsfiddle.net/5pbkddgo Commented Aug 4, 2015 at 5:54
  • jsfiddle.net/arunpjohny/cz7sasct - looks fine Commented Aug 4, 2015 at 5:55
  • @ArunPJohny is there any way it is not sorting correctly because of string Commented Aug 4, 2015 at 6: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"). Commented Aug 4, 2015 at 6:41
  • 1
    @coolguy yes... if it is doing a string comparison try jsfiddle.net/arunpjohny/cz7sasct/3 Commented Aug 4, 2015 at 6:42

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

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.