2

I have a few arrays:

cl = ["Chile", "15", "83"];
ar = ["Argentinia", "16.5", "90"];
py = ["Paraguay", "19", "81.5"];

route = ["cl;ar", "ar;py"];

Is it possible to loop through one array and get the specific values from the other arrays? I've tried this which didn't work:

$.each(route, function(index,value) {
    place = v.split(';');
    start = place[0];
    end = place[1];

    console.log('from '+start[0]+' to '+end[0]);
});

The log should display: "from Chile to Argentinia", "from Argentinia to Paraguay" but it writes just "from c to a", "from a to p".

What did I wrong, how can I read the values from the other arrays?

1
  • Thank you Matt! eval(...) works perfectly. Commented Apr 15, 2014 at 20:06

2 Answers 2

3

You could potentially use a hash table:

var countries = {
    cl: {name: 'Chile', prop1: 15, prop2: 83},
    ar: {name: 'Argentinia', prop1: 16.5, prop2: 90},
    py: {name: 'Paraguay', prop1: 19, prop2: 81.5}
}

Then you can look it up when you need it:

$.each(route, function(index,value) {
    place = value.split(';');
    start = place[0];
    end = place[1];

    console.log('from '+ countries[start].name + ' to ' + countries[end].name);
});

Fiddle

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

3 Comments

If possible, I'd move the other values from the arrays in the question to properties of your countries object...
@ShaneBlake Didn't want to make up random key names. Good point though, I've moved them in.
So often when the solution is elusive, I find my data model was poorly designed...
0

Try using a hashtable:

var hashtable = {};
hashtable['cl'] = ["Chile", "15", "83"];
hashtable['ar'] = ["Argentinia", "16.5", "90"];
hashtable['py'] = ["Paraguay", "19", "81.5"];

route = ["cl;ar", "ar;py"];

$.each(route, function(index,value) {
    var fromTo = value.split(";");
    alert('from '+hashtable[fromTo[0]][0]+' to '+hashtable[fromTo[1]][0]);
});

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.