Entry
How do I sort a two-dimensional array?
Aug 30th, 2000 08:23
Martin Honnen, Bryce Schober,
You need to decide what your sort criteria are and then write an
appropriate comparison function to pass to the sort method; example:
var a = [
['Xibo', 'Lames'],
['Kibo', 'James'],
['Frank', 'Ted'],
['Honnen', 'Martin'],
['Honnen', 'James']
];
alert(a);
function compareNames(a1, a2) {
return a1[0] < a2[0] ? -1 :
a1[0] > a2[0] ? 1 :
a1[1] < a2[1] ? -1 :
a1[1] > a2[1] ? 1 : 0;
}
a.sort(compareNames);
alert(a);