Posted by: prajapatinilesh | June 25, 2009

Javascript + Array sort on Key

Hi,

Please follow following example to understand the problem.

<script>
function keySort(array, flag) {
var keys = new Array();

for(k in array) {
keys.push(k);
}

keys.sort( function (a, b) {
if (flag && flag != ‘undefined’) {
if(flag == ‘integer’) {
a = parseInt(a);
b = parseInt(b);
}
}
return (a > b) – (a < b);
} );

return keys;
}//End of function keySort

/*jsArray = new Array();
jsArray[‘A’] = ‘Test1’;
jsArray[‘Z’] = ‘Test3’;
jsArray[‘P’] = ‘Test4’;
jsArray[‘U’] = ‘Test2’;
jsArray[‘B’] = ‘Test5’;*/

jsArray = new Array();
jsKeyArray = new Array();

jsArray[80] = ‘nil1’;
jsArray[120] = ‘nil2’;
jsArray[160] = ‘nil3’;

for (x in jsArray) {
alert(x + ‘ –> ‘ + jsArray[x]);
}

jsKeyArray = keySort(jsArray);

/*for (x in jsKeyArray) {
alert(x + ‘ –> ‘ + jsKeyArray[x]);
}*/

//It will display wrong result….
for (var i = 0; i < jsKeyArray.length; i++) {
alert(jsKeyArray[i] + ‘ –> ‘ + jsArray[jsKeyArray[i]]);
}

jsKeyArray = keySort(jsArray, ‘integer’);

//correct result….
for (var i = 0; i < jsKeyArray.length; i++) {
alert(jsKeyArray[i] + ‘ (integer) –> ‘ + jsArray[jsKeyArray[i]]);
}

//——————————————————————–

//Value integer sorting…..

function sortASC(a, b){ return (a-b); }
function sortDESC(a, b){ return (b-a); }

integerArray = new Array(1,545,1435,3453,342,441,90);

integerArray.sort( sortASC );
document.write(‘ <br /> Ascending : ‘ + integerArray);

integerArray.sort( sortDESC );
document.write(‘ <br /> Descending : ‘ + integerArray );

</script>

Thanks,

Nilesh Prajapati

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: