1

Possible Duplicate:
Sort array of objects

[ { name: 'jane', id:'3' }
  { name: 'zac', id: '5' }
  { name: 'amber', id: '2 }
]

How do I sort this alphabetically by name, ascending?

The result should be:

[ { name: 'amber', id: '2' }
  { name: 'jane', id:'3' }
  { name: 'zac', id: '5' }
]
0

2 Answers 2

2

Use Array.sort. You can pass it a custom function to use to compare objects. To compare strings, you can use String.localeCompare. Put it together, and you get this:

var data=[
    { name: 'jane',  id: 3 }
    { name: 'zac',   id: 5 }
    { name: 'amber', id: 2 }
];
console.log("Unsorted:", data);
data.sort(function(a, b) {
    return a.name.localeCompare(b.name);
});
console.log("Sorted:", data);
0
1
[{ name: 'jane',  id:'3' },
 { name: 'zac',   id: '5'},
 { name: 'amber', id: '2'}].sort(
    function (a,b) {
        return a.name.localeCompare(b.name)
    }
);
1
  • 1
    I hadn't known about localeCompare. Neat. Commented Sep 18, 2011 at 22:43

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.