faqts : Computers : Programming : Languages : JavaScript : Language Core : Arrays

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

66 of 107 people (62%) answered Yes
Recently 6 of 10 people (60%) answered Yes

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);