0

I have some data like

4 0.128 0.039
5 0.111 0.037
6 0.095 0.036

I need to get the second and third value by a known first value. If I have a value of 4 I want to get back two variables: a = 0.111 and b = 0.037

What would be the best variable type for storing the data shown above to get simple access to the data? An object or an multidimensional array?

3 Answers 3

2

For ease of access, I'd go with an object containing arrays:

{
    '4': [ 0.128, 0.039 ],
    '5': [ 0.111, 0.037 ],
    ... 
}

A second reason for the use of objects over arrays is ease of iteration. Imagine this:

var myData = [];
myData[4]  = [ 0.128, 0.039 ];
myData[10] = [ 42, 23 ];

for (var i = 0; i < myData.length; i++)
{
    console.log(myData[i]);
}

Would give you

null
null
null
null
[ 0.128, 0.039 ]
null
null
null
null
null
[ 42, 23 ]

... which is probably not what you want ;)

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

2 Comments

If var x = 4, how do I access the values? data.x[0] and data.x[1]?
@user3848987 use bracket notation: data[x][0], and so forth ;)
1

What you would want to do is save it as a json object or just as an array as shown below:

Creating:

var obj = { "4":[0.128, 0.039], "5":[0.111, 0.037],"6":[0.095, 0.036] }

Retrieving:

obj.4 -> [0.128, 0.039] OR obj['4'] OR obj[0]
obj.5[0] -> 0.111 OR obj['5'][0] OR obj[1][0]
obj.5[1] -> 0.037 OR obj['5'][1] OR obj[1][1]

Cycling through retrieved obj:

for (var key in obj) {
    alert(obj[key]); 
}

Comments

1

I personally use arrays if the order of the elements is of importance, otherwise I use objects (objects are not good for preserving order).

  • Arrays come with methods like push(),pop(),sort(),splice().
  • Objects are good if you have a unique key.

In the end it comes down to what is the best tool for what is that you want to accomplish.

Comments

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.