| How to look up data in string or table? Array? Hash? Something else? |
MichaelBluejay

msg:4451219 | 9:44 am on May 9, 2012 (gmt 0) | Let's say I have data such as the following:
female 25 486-72 female 30 398-27 female 35 287-39 male 25 182-28 male 30 298-21 male 35 929-88 How do I look up the first two columns to get the third, without looping through the whole thing? For example, how do I look up "male" and "25", to get the result "182-28"? I was thinking of putting my data in a hidden <textarea>, but I'm not opposed to hard-coding it into variables manually. I've hit up the search engines but can't find anything that seems relevant. Thank you very much for your help!
|
g1smd

msg:4451226 | 10:01 am on May 9, 2012 (gmt 0) | Use an array?
|
Fotiman

msg:4451298 | 1:38 pm on May 9, 2012 (gmt 0) | As an array of arrays: var data = [ ["female", "25", "182-28"], ["female", "30", "398-27"], ["female", "35", "287-39"], ["male", "25", "182-28"], ["male", "30", "298-21"], ["male", "35", "929-88"] ]; function search(searchValue1, searchValue2) { var i; for (i = 0; i < data.length; i++) { if (data[i][0] === searchValue1 && data[i][1] === searchValue2) { return data[i][2]; } } } var result = search("male", "25");
|
| As a hash: var data = { "female-25": "182-28", "female-30": "398-27", "female-35": "287-39", "male-25": "182-28", "male-30": "298-21", "male-35": "929-88" }; function search(searchValue1, searchValue2) { return data[searchValue1 + "-" + searchValue2]; } var result = search("male", "25");
|
| Or another approach: var data = { "female": { "25": "182-28", "30": "398-27", "35": "287-39" }, "male": { "25": "182-28", "30": "298-21", "35": "929-88" } }; function search(searchValue1, searchValue2) { return data[searchValue1][searchValue2]; } var result = search("male", "25");
|
|
|
MichaelBluejay

msg:4451566 | 11:17 pm on May 9, 2012 (gmt 0) | Thanks Fotiman, that's super-helpful! I was hoping that there'd be a way to access the data directly (without a function), but this is not too bad. I'm going to take a stab at writing my own function to get the data from a hidden textarea into one of those structures, but if I fail I might be back to ask for more help.
|
Fotiman

msg:4451579 | 11:55 pm on May 9, 2012 (gmt 0) | Well, you could bypass the search function and just do exactly what that function is doing. For example, in the last example I posted, instead of calling the search function you could just do: data["male"]["25"] to get "182-28". The function was just a way to hide the implementation details (you don't need to know if the data is stored in a hash, or in an array, you just need to pass in the 2 values).
|
MichaelBluejay

msg:4451647 | 4:12 am on May 10, 2012 (gmt 0) | I see now, I didn't look at it very closely to begin with. Thanks again!
|
|
|