Posted by: Vijay Modi | May 31, 2007

Javascript + Array sort on Key

Today one my friend ask me how to sort array by key using javascript. I think about it and write the following example. Its working fine and the problem of my friend resolve.

===============================================

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN”>
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME=”Generator” CONTENT=”EditPlus”>
<META NAME=”Author” CONTENT=”">
<META NAME=”Keywords” CONTENT=”">
<META NAME=”Description” CONTENT=”">
<script language=”javascript”>
jsArray = new Array();
jsArray['A'] = ‘Test1′;
jsArray['Z'] = ‘Test3′;
jsArray['P'] = ‘Test4′;
jsArray['U'] = ‘Test2′;
jsArray['B'] = ‘Test5′;

array = jsArray;
var keys = new Array();
for(k in array)
{
     keys.push(k);
}

keys.sort( function (a, b){return (a > b) - (a < b);} );

for (var i = 0; i < keys.length; i++)
{
     alert(keys[i] + ” , ” + array[keys[i]]);
}
</script>
</HEAD>

<BODY>

</BODY>
</HTML>

===============================================

Howdy, Write you comments regarding this article. Great na????

8)Regards,
Vijay Modi

Responses

your solution is realy good but pl tell me what following statement do
keys.sort( function (a, b){return (a > b) - (a

Hi here

If two numbers(values) are compared, this simply needs to subtract the second from the first number:

Thanks,
Vijay Modi

Leave a response

Your response:

Categories