0

I have a code which looks like:

var result = {};
for (var i = 0; i < questions.length; i++)
{
 if(result.hasOwnProperty(questions[i].group)) {
 var questionsInGroup = result[questions[i].group];
 log.debug(typeof questionsInGroup);
 result[questions[i].group] = questionsInGroup.push(questions[i]);
} else {
 result[questions[i].group] = new Array(questions[i]);
}

Here I am trying to create an Associative Array where the keys are strings, and values are arrays of objects.

When I launch this code I get error:

result[questions[i].group] = questionsInGroup.push(questions[i]);
 ^
TypeError: Object 2 has no method 'push'

And debug message looks like:

debug: [node/server.js] number

Why the 'questionsInGroup' is a number if I have created it as Array:

result[questions[i].group] = new Array(questions[i]);
asked Oct 6, 2014 at 7:53

1 Answer 1

4

push returns the new length of the array, not the array, so this line:

result[questions[i].group] = questionsInGroup.push(questions[i]);

...overwrites your reference to the array with a number. Simply remove the assignment.


Side note: It's generally best to avoid the Array constructor entirely (use [] instead), and it's always best to avoid it if you're calling it with just one argument. If you give the Array constructor a single argument that's a number, you'll get back an empty array with its length set to that number; but if you call it with any other type of argument, you get back an array with length of 1 containing that argument.

Example:

var a;
a = new Array(2);
display(a.join(", ") + " (" + a.length + ")");
a = new Array("2");
display(a.join(", ") + " (" + a.length + ")");
function display(msg) {
 var p = document.createElement("p");
 p.innerHTML = String(msg);
 document.body.appendChild(p);
}

For that reason, I'd replace:

result[questions[i].group] = new Array(questions[i]);

with

result[questions[i].group] = [questions[i]];
answered Oct 6, 2014 at 7:56
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.