0

I am trying to sort a hashtable (originally called "resultVal") alphabetically in javascript.

// initializing an array with all the keys. //
var keys = [];
// populating it with all the keys in the hashtable. //
for (var key in resultVal) {
    if (resultVal.hasOwnProperty(key)) {
        keys.push(key);
    }
}
// Alphabetically sorting the array populated with hash table keys. //
keys.sort();
var temp = {};

for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var value = resultVal[key];
    if (key != "") {
        temp[key].push(value);
    }
}

My issue is with the last statement :-

temp[key].push(value);

What I am doing is, sort the keys alphabetically and re-feed the key and its respective values into a temp hashtable..."temp".

The push statement isn't being recognized. can anyone help?

1
  • 1
    Since object properties are not sorted, there really is no need to do all of this. If you need to access the values in a sorted ordered at some point, extract and sort the keys later on. Commented Jun 10, 2013 at 18:33

1 Answer 1

2

temp is defined as an object, not an array. There's no need to push() onto it:

temp[key] = value;
Sign up to request clarification or add additional context in comments.

4 Comments

thanks man, worked! Could you explain why exactly it is not necessary to push into an object as opposed to an array. Because when I created the hashtable I merged two separate arrays and used the push functionality. I apologize for the noobish=ness.
The value stored at temp[key] is not an array. You would have to define an array object in that position of the temp array if you want to push onto it.
Also, be aware of the fact that properties in JS might have different position (depending on JS engine/browser and its name). So if you need specific positions of props, always use an array.
in my code, the value is a list of dates aka a 1 dimensional array with dates. hence i thought I had to push them into the temp of key position. however now it makes sense! thanks all!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.