2

I want to sort the Array by Id

var arr = [{"name":"a", "id":"2"}, {"name":"r", "id":"11"}, {"name":"y", "id":"23"}, {"name":"e", "id":"1"}];

I am using following code

function compareNum(a,b) {
          if (a.id < b.id)
          {
              return -1;
          }
          if (a.id > b.id)
          {
              return 1;
          }

          return 0;
}

Answer Sorting: 1, 11, 2, 23

But I need: 1,2,11,23

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Kashif Hashmi
  • 75
  • 1
  • 2
  • 10

3 Answers3

1

You need to use parseInt() to convert each id from a string to an integer.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
1

Just add some parseInt() and it will work:

function compareNum(a, b) {
    if (parseInt(a.id) < parseInt(b.id)) {
        return -1;
    }
    if (parseInt(a.id) > parseInt(b.id)) {
        return 1;
    }
    return 0;
}

Demo

--

But actually a simplified version would also work:

arr.sort(function(a,b) {
    return a.id - b.id;
});

Demo

Sergio
  • 28,539
  • 11
  • 85
  • 132
1

You can use the predefined sort() JavaScript function:

arr = arr.sort(function(current, next){
    return current.id - next.id;
});

See a demo online here: http://jsfiddle.net/5J8kk/3/


Source: https://stackoverflow.com/a/13171179/1505348

Community
  • 1
  • 1
Lucio
  • 4,753
  • 3
  • 48
  • 77