Wrox Programmer Forums
|
Javascript General Javascript discussions.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Javascript section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old February 10th, 2004, 04:23 PM
Registered User
 
Join Date: Oct 2003
Posts: 4
Thanks: 0
Thanked 0 Times in 0 Posts
Default Sort Method question

In JavaScript to sort a single demensional array named 'users' we use the sort method as follows --> users.sort();

Let's say we have a two dimensional array named 'users' with three fields defined as follows,

users[indx] = new Array();
users[indx][0] = name;
users[indx][1] = dept;
users[indx][2] = date;

The default sort for two demensional arrays seems to sort by the first field, ie name. Is it possible to sort by another field, ie dept or date. What is the syntax.

 
Old February 10th, 2004, 07:03 PM
joefawcett's Avatar
Wrox Author
 
Join Date: Jun 2003
Posts: 3,074
Thanks: 1
Thanked 38 Times in 37 Posts
Default

When you call sort you can optionallly pass a function pointer with a custom sort routine. This function compares the two items and returns 1 if the first is greater than the second, -1 if the second is greater and 0 if equal. Although a bit long winded a general example for your case is below:
Code:
function compareOnField2(Item1, Item2)
{
  var item1 = Item1[1];
  var item2 = Item2[1];
  if (item1 > item2) return 1;
  if (item1 < item2) return -1;
  return 0;
}
Then call
Code:
users.sort(compareOnField2)
Make sure there are no quotes around the function name.

--

Joe





Similar Threads
Thread Thread Starter Forum Replies Last Post
Simple sort question garybetz XSLT 2 October 27th, 2007 12:52 PM
XSLT Dynamic xsl:sort Method kwilliams XSLT 2 July 20th, 2005 03:19 PM
xsl:sort Question kwilliams XSLT 6 July 18th, 2005 08:39 AM
sort by question elladi Classic ASP Databases 1 March 29th, 2005 11:12 AM
Sort order Question Tere Crystal Reports 1 February 14th, 2005 03:18 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.