Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

Given the following:

var array = [{"name":"zoe", "hotdogs":5},{"name":"april", "hotdogs":5},{"name":"ryan", "hot dogs":8}]

How can I sort the elements of the array by name using JavaScript?

var array = [{"name":"april", "hotdogs":5},{"name":"ryan", "hotdogs":8},{"name":"zoe", "hotdogs":5}]

Is there a way to apply some function to sort the objects? Are there helper libraries that help with performance?

I tried the following:

array.sort(function(a, b) {
    return a.name > b.name
});

But it appeared to have no effect on the resulting array when I try to print it out whatsoever.

share|improve this question

marked as duplicate by Felix Kling, Ben Lee, Perception, Stuart, Audrius Meškauskas Mar 4 '13 at 2:21

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.

2  
Try return (a.name>b.name)-(b.name>a.name). .sort interprets 0 (AKA +false) as "equals" –  Jan Dvorak Mar 3 '13 at 17:30
    
@Jan, that did it. –  Setsuna Mar 3 '13 at 17:32
    
@JanDvorak is correct jsfiddle.net/avWXu –  CJ. Mar 3 '13 at 17:33

2 Answers 2

up vote 2 down vote accepted

Use .localeCompare().

array.sort(function(a, b) {
    return a.name.localeCompare(b.name)
});
share|improve this answer

The function should return integer, like C strcmp, so do:

if a.name > b.name {
  return 1;
} else if ( a.name == b.name) {
  return 0;
}
return -1
share|improve this answer
    
"zoe"-"april" => NaN –  Jan Dvorak Mar 3 '13 at 17:32

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