1

Here's what I'm looking to do..

var dual = new Array; 
dual=[voter,thisID];
var matrix = new Array;
matrix[dual]=voteint; //this works..

but I'd like to easily access values by either or both key (array) element:

matrix[*,thisID])=answer; 

except wildcards don't exist in this way, right?

one could do...

matrix[voter+'.'+thisID]=voteint;

and do regex matching around the '.' but is there a better/easier/faster way?

2
  • What you could do is creating a function that iterates through all matrix elements and check whether it matches the selector. It would return a set of all matched elements. Commented Jun 20, 2011 at 20:41
  • True, that would do it nicely. I was worrying about performance too early and hoping there were some more native way.thanks! Commented Jun 21, 2011 at 9:11

1 Answer 1

2
> var dual = new Array; 
> dual=[voter,thisID];

The second assignment replaces the array originally assigned to dual, making the first assignment useless. It can be written:

var dual = [voter, thisID];

but only if voter and dual have been declared or created as variables earlier.

> var matrix = new Array;
> matrix[dual]=voteint; //this works..

As above, the first assignment to matrix is redundant.

It "works" by assigning a property to matrix that is dual.toString(), so if you'd written:

var voter = 'foo';
var thisID = 'baz';
var dual = [foo, baz];

then

matrix[dual] = voteint;

is equivalent to:

matrix['foo,baz'] = voteing;

if voteint has been assigned a value earlier.

but I'd like to easily access values by either or both key (array) element:

> matrix[*,thisID])=answer;

except wildcards don't exist in this way, right?

Not in that context, no.

one could do...

matrix[voter+'.'+thisID]=voteint;

If the . was replaced by a comma, yes.

and do regex matching around the '.' but is there a better/easier/faster way?

It is considered bad practice to use an Array where an Object is indicated, so better to use an Object here.

Your only reasonable option is to iterate over the object's properties using for..in to test each property name to find the one you want. Note that you should also include a hasOwnProperty test to exclude inherited enumerable properties.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Good pointers. Would it be a good idea to treat the key as a number with decimals? Thinking one could retain the array characteristics such as length that way, and perhaps sorting it would increase perfomance of search etc.

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.