How to sort an object?

R

RC

I have simple hashtable object

function myHashTable(key, value) {
this.key = key;
this.value = value;
}

var myObjectArray = new Array(5);

myObjectArray[0] = new myHashTable(1, "2006-06-07");
myObjectArray[1] = new myHashTable(2, "2005-04-10");
.....

Now my question is how do I sort the value, not the key
in myObjectArray?

I did

myObjectArray.sort(myHashTable);

But the output result are NOT correct.

The correct result after sort should be:

myObjectArray[0].key is 2, myObjectArray.value is 2005-04-10
myObjectArray[1].key is 1, myObjectArray.value is 2006-06-07

Thank Q very much in advance!
 
L

Lasse Reichstein Nielsen

RC said:
I have simple hashtable object

function myHashTable(key, value) {
this.key = key;
this.value = value;
}

This is really a hash table entry, not a full hash table?
var myObjectArray = new Array(5);

myObjectArray[0] = new myHashTable(1, "2006-06-07");
myObjectArray[1] = new myHashTable(2, "2005-04-10");
....

Now my question is how do I sort the value, not the key
in myObjectArray?

myObjectArray.sort(functionThatComparesMyHashTableByValue);

The hard part is making that function :)

A generic comparison function, for anything that works with the less
than operator, is:

function compare(a,b) {
return (a < b) ? -1 : (b < a) ? 1 : 0;
}

You can then build a comparison function for the values:

function functionThatComparesMyHashTableByValue(a,b) {
return compare(a.value, b.value);
}

A shorter name would be recommended :)
I did

myObjectArray.sort(myHashTable);

The argument to the sort function must be a comparison function
returning a number, the sign of that number representing whether
one argument is smaller or bigger than the other.

You are passing a function that takes two arguments and assigns them
to some object (in this case the global object, as you can test by
alerting window.key and window.value afterwards :).
But the output result are NOT correct.

Unsurprisingly! (or really, with only two elements in the array,
there's a 50% chance the sort would be correct if it's random :)

Hope this helps. Code not tested.
/L
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,150
Latest member
MakersCBDReviews
Top