1
[ 
    {   
        time: '5'
    },
    {
        time: '2'
    },
    {
        time: '3'
    }
]

Let's say I have an array of objects. I want to sort it by time, ascending. How can I do that in javascript?

Is there a generic function?

Example

var sorted_array = sortByKey(my_array, 'time', 'asc');
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

4 Answers4

1

You can do something like this:

my_array.sort(function(a,b) {return a.time - b.time});
Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
1

Something like:

 jsArray = [ 
{   
    time: '5'
},
{
    time: '2'
},
{
    time: '3'
}
 ]

    jsArray.sort( function( tm1, tm2 ){
      return tm2.time - tm1.time;
    });
james emanon
  • 11,185
  • 11
  • 56
  • 97
0

You can use the built in array.sort(somefunction)

var data = [ 
    {   
        time: '5'
    },
    {
        time: '2'
    },
    {
        time: '3'
    }
];

data.sort(function(a,b){
    return a.time - b.time;
});
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
zz3599
  • 647
  • 5
  • 20
0
var myArr = [
    {
        time: '5'
    },
    {
        time: '2'
    },
    {
        time: '3'
    }
];

myArr.sort(function (a, b) {
    return parseInt(a.time, 10) - parseInt(b.time, 10);
});
kinakuta
  • 9,029
  • 1
  • 39
  • 48