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”>
<TITLE> New Document </TITLE>
<META NAME=”Generator” CONTENT=”EditPlus”>
<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.sort( function (a, b){return (a > b) – (a < b);} );

for (var i = 0; i < keys.length; i++)
     alert(keys[i] + ” , ” + array[keys[i]]);




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

Vijay Modi


About Vijay Modi

Having 12+ years of experience in web application development. Expertise in various domains like E-Commerce, E-Learning, Insurance. I have expertise in web application development, window application development, Performance improvement, bug fixing etc. I have worked on various Microsoft technologies including ASP.Net, MVC, WebApi, WCF, Entity Framework, WPF, Window Application Development, AWS, Azure, AngularJS 2.0 / 1.5.2, .NetCore framework, jQuery. I am believing in quality work and achieving deadlines. Also like to work on new technologies and quick learner.
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

3 Responses to Javascript + Array sort on Key

  1. bhumit patel says:

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

  2. Vijay Modi says:

    Hi here

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

    Vijay Modi

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s