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
  • 238,746
  • 336
  • 750
  • 1,061

4 Answers4

1

You can do something like this:

my_array.sort(function(a,b) {return a.time - b.time});
Adam Plocher
  • 13,693
  • 5
  • 46
  • 78
1

Something like:

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

    jsArray.sort( function( tm1, tm2 ){
      return tm2.time - tm1.time;
    });
james emanon
  • 10,145
  • 7
  • 45
  • 77
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
  • 344,413
  • 96
  • 627
  • 693
zz3599
  • 647
  • 5
  • 19
0
var myArr = [
    {
        time: '5'
    },
    {
        time: '2'
    },
    {
        time: '3'
    }
];

myArr.sort(function (a, b) {
    return parseInt(a.time, 10) - parseInt(b.time, 10);
});
kinakuta
  • 8,949
  • 1
  • 36
  • 48