Sign up ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

This question already has an answer here:

[ 
    {   
        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');
share|improve this question

marked as duplicate by Matt Ball, vstm, CodaFi, Roman C, Stuart Mar 9 '13 at 7:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4 Answers 4

up vote 0 down vote accepted

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;
});
share|improve this answer

You can do something like this:

my_array.sort(function(a,b) {return a.time - b.time});
share|improve this answer

Something like:

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

    jsArray.sort( function( tm1, tm2 ){
      return tm2.time - tm1.time;
    });
share|improve this answer
var myArr = [
    {
        time: '5'
    },
    {
        time: '2'
    },
    {
        time: '3'
    }
];

myArr.sort(function (a, b) {
    return parseInt(a.time, 10) - parseInt(b.time, 10);
});
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.