How to sort an array of objects with jquery or javascript

Karoline Brynildsen picture Karoline Brynildsen · Mar 31, 2011 · Viewed 293.7k times · Source

I have an array of objects:

var array = [(id, name, value),(id, name, value)]; //and so on

How do I get the array to be sorted in ascending order of the atribute name (array[i][1])?

I've tried to do this: array[i][1].sort(), but that doesn't work.

Please help me!

Edit: the array can contain more than two objects! It can contain hundreds.

Edit: Why is this question marked as a duplicate, when it was asked 2 years before the "duplicated" question?

Answer

Ketan picture Ketan · Mar 31, 2011
//This will sort your array
function SortByName(a, b){
  var aName = a.name.toLowerCase();
  var bName = b.name.toLowerCase(); 
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

array.sort(SortByName);