Jagged Array in JavaScript

Hi Experts,

Is it possible to have a Jagged Array in JS, and how?

For example I have multiple of locations, and each has their own sets of sales agents, so I want to setup an array similar to:

location['Downtown'][] = "Alex"
location['Downtown'][] = "Bob"
location['Downtown'][] = "Ray"

location['Midtown'][] = "Dave"

location['Uptown'][] = "Cleopatra"
location['Uptown'][] = "Jessica"

Further, I'd need to get the length of each sub-array, so location['Downtown']length would be 3; location['Midtown']length would be 1; and location['Uptown']length would be 2

Thank you.
APD TorontoSoftware DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

APD TorontoSoftware DeveloperAuthor Commented:
Actually, with research I came up with the following code, but in Firefox it looks like endless loop.

The reason why I am using multiple <script> tags within my form is because I will be actually populating these from a database using php foreach()

<?php?>

<script type="text/javascript">

    var count = 0;
    var location = new Array();
    
</script>

<form>
    
    <input type="button" id="btnCount" name="btnCount" value="Count 0" onclick="incCount();">
    
    <script type="text/javascript">
        //Downtown
        var agents = new Array();
        agents[] = 'aleks';
        agents[] = 'Bob';
        agents[] = 'Ray';
        location['downtown'] = agents;      
    </script>
    
    <script type="text/javascript">
        //Midtown
        var agents = new Array();
        agents[] = 'Dave';
        location['midtown'] = agents;      
    </script>
    
    <script type="text/javascript">
        //Uptown
        var agents = new Array();
        agents[] = 'Cleopatra';
        agents[] = 'Jessica';
        location['uptown'] = agents;      
    </script>    
    
    <input type="button" onClick="showArray();" value="show array">
    <textarea id="txtResults"></textarea>
    
</form>

<script type="text/javascript">
    
    function showArray(){
        var results;
        var locCount = 0;
        var agentCount = 0;
        var locName = '';
        var agentName = '';
        
        locCount = location.count;
        
        results = 'loc count = ' + locCount + '\n\n';
        
        document.getElementById('txtResults') = results;
    }
    
    function incCount(){
        count++;
        document.getElementById('btnCount').value = 'Count ' + count;
        
    }
    
</script>

Open in new window


As a result of my prototype, I am hoping to get the following in my textarea
Loc count = 3

downtown : 3 agents: aleks, Bob, Ray

midtown: 1 agents: Dave

uptown: 2 agents: Cleopatra, Jessica

Open in new window

0
Dave BaldwinFixer of ProblemsCommented:
First, "location" is a reserved word / function in javascript and you can not use it as a variable name.  I'm working on the rest of it.  javascript doesn't make it easy to do this.
0
Dave BaldwinFixer of ProblemsCommented:
And here's why (from http://www.w3schools.com/js/js_arrays.asp ):
JavaScript does not support arrays with named indexes.
In JavaScript, arrays use numbered indexes.  
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Dave BaldwinFixer of ProblemsCommented:
At the moment, all I'm getting is nonsense results for your 'jagged array'.
0
Ray PaseurCommented:
JavaScript seems to be one of those programming languages that people somehow think they can use in a deployed application without actually learning the language.  And JavaScript is deeply complex.  But like most things, it will all work out better if you know what you're doing.  Here are some ways to learn JavaScript.

If you like exercises, buy this book and use the accompanying web site.  You can finish it in about a week, certainly no more than two weeks.
http://www.amazon.com/Smarter-Way-Learn-JavaScript-technology-ebook/dp/B00H1W9I6C

If you like to read and create your own exercises, buy this book and give yourself some time to get the foundation in place.  It's over 1,000 pages (and not one of them is wasted).  So if you can internalize twenty pages a day, you can get through it in about two months.
http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527

For better or worse, you cannot hide your JavaScript application until it works -- as soon as you publish a web site with your JavaScript in it, you have deployed it onto your clients' browsers.  There are some tools and tests that can help you avoid deploying an unworkable application.  You might want to learn about Grunt, Gulp, Karma and Jasmine.  A good place to start is here:
http://www.smashingmagazine.com/2012/06/27/introduction-to-javascript-unit-testing/

JavaScript is the world's most widely used computer language -- it's on every browser and comes into play in every HTTP request, so it sort of behooves us to learn it very, very well.  PHP is my main language; JavaScript is on hundreds of times more computers than PHP.  Please be comfortable with the time you must take to learn JavaScript.  When I talk to my colleagues and the conversation turns to "what programming languages...?" the answer always ends with ", and JavaScript."
0
Dave BaldwinFixer of ProblemsCommented:
After mucking around, I have this that works.  It's not exactly what you wanted.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" >
<title>JS Arrays</title>
</head>
<body>
<h1>JS Arrays</h1>
<script type="text/javascript">
<!--
var theplace = ['Downtown','Midtown','Uptown'];

var i = 0;
var Downtown = new Array(' '); 
Downtown[i++] = "Alex";
Downtown[i++] = "Bob";
Downtown[i++] = "Ray";
document.write("Downtown.length = " + Downtown.length + "<br>");

i = 0;
var Midtown = new Array(' '); 
Midtown[i++] = ["Dave"];
document.write("Midtown.length = " + Midtown.length + "<br>");

i = 0;
var Uptown = new Array(' '); 
Uptown[i++] = ["Cleopatra"];
Uptown[i++] = ["Jessica"];
document.write("Uptown.length = " + Uptown.length + "<br>");

// -->
</script>
</body>
</html>

Open in new window

0
APD TorontoSoftware DeveloperAuthor Commented:
Thanks Dave,

I often use "loc" as a variable name, so that is not an issue.  This does not have to be an associated array, actually it wont be, I just used it to be descriptive.

IN reality, I wanted a jagged array of locs, where the primary array will have the location id, and the sub array of unknown number of agents will have one element for each agent that contains their id. So, the array should really look like this:

loc[0] = 123 //Downtown
   agent[0] = 25 //Which is alex
   agent[1] = 10 //Bob
   agent[2] = 5 //Ray

loc[1] = 456 //Midtown
   agent[0] = 60 //Dave

loc[2] = 352 //Uptown
   agent[0] = 135 //Cleopatra
   agent[1] = 453 //Jessica

Open in new window


FYI, I have about 230 locations, and maybe 10 agents per location. I dont really need to store the string literals, I just need IDs as above

Can you get me started please?
0
APD TorontoSoftware DeveloperAuthor Commented:
Ray,

I understand were you are coming from, and for the past year I have been teaching myself intensively MySQL, PHP and HTML5 with CSS, but I need a little break and earn little... My next course is Javascript for sure, and thank you for the resources, I will definitely consider.

FYI, by the way an excellent publisher Mike Murach.
0
Dave BaldwinFixer of ProblemsCommented:
In your sample code above, every agent[0], I mean Every agent[0] will be the Same agent[0] and if you assign a value to it, it will over-write the previous value.  You have to give the arrays different names, you can not reuse the names.  Or... you could section it by numbers where agent[0] thru agent[99] is for the first location, agent[100] thru agent[199] is for the second and so on.

Generating the arrays thru PHP is not difficult.  How are you going to try access them?  That plan is probably more important.  And since PHP is considerably more powerful in that area, it should be a significant part of your plan.
0
Dave BaldwinFixer of ProblemsCommented:
I've added another way to process the array in this one.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" >
<title>JS Arrays</title>
</head>
<body>
<h1>JS Arrays</h1>
<script type="text/javascript">
<!--
var theplace = ['Downtown','Midtown','Uptown'];

var i = 0;
var Downtown = new Array(' '); 
Downtown[i++] = "Alex";
Downtown[i++] = "Bob";
Downtown[i++] = "Ray";
document.write("Downtown.length = " + Downtown.length + "<br>");

i = 0;
var Midtown = new Array(' '); 
Midtown[i++] = ["Dave"];
document.write("Midtown.length = " + Midtown.length + "<br>");

i = 0;
var Uptown = new Array(' '); 
Uptown[i++] = ["Cleopatra"];
Uptown[i++] = ["Jessica"];
document.write("Uptown.length = " + Uptown.length + "<br>");

var loc = [
	["Alex","Bob","Ray"],
	["Dave"],
	["Cleopatra","Jessica"]
	];

for(i=0;i<loc.length;i++) {
	document.write("loc[" + i +"].length = " + loc[i].length + "<br>");
	}	
// -->
</script>
</body>
</html>

Open in new window

0
Dave BaldwinFixer of ProblemsCommented:
Turns out there is another question right now about combining PHP and javascript.  Since everything on an HTML page is just text to PHP, you can use PHP to 'insert' text where ever you want it.  Save this one as *.php.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" >
<title>JS Arrays</title>
</head>
<body>
<h1>JS Arrays</h1>
<script type="text/javascript">
<!--
<?php 
$loc = array();
$loc['downtown'] = array("Alex","Bob","Ray");
$loc['midtown'] = array("Dave");
$loc['uptown'] = array("Cleopatra","Jessica");

echo "var loc = [";
echo '["'.$loc['downtown'][0].'","',$loc['downtown'][1].'","'.$loc['downtown'][2].'"],';
echo '["',$loc['midtown'][0].'"],';
echo '["'.$loc['uptown'][0].'","'.$loc['uptown'][1].'"]';
echo '];';

 ?>

for(i=0;i<loc.length;i++) {
	document.write("loc[" + i +"].length = " + loc[i].length + "<br>");
	}

// -->
</script>
</body>
</html>

Open in new window

0
Scott Fell, EE MVEDeveloper & EE ModeratorCommented:
Let's say your php generates a page of json that looks like below.  I have a sample at http://jsbin.com/jebupoheja/1.js
{
    "locations": {
        "location": [
            {
                "id": "123",
                "agent": [25,12,5]
                
            },
             {
                "id": "456",
                "agent": [60]
                
            },
             {
                "id": "352",
                "agent": [135,453]
                
            }
          
        
        ]
    }
}

Open in new window

JQUERY
(function() {
var url = "http://jsbin.com/jebupoheja/1.js";

  $.getJSON( url, {
    format: "json"
  

}).done(function( data ) {
      $.each( data.locations.location, function( i, item ) {
       $('#results').append(item.id+"<br>"+"There are "+item.agent.length+" agents:  "+item.agent+"<hr>");
        
      });
    });
})();

Open in new window

HTML
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="results"></div>
</body>
</html>

Open in new window

OUTPUT
<div id="results">123<br>There are 3 agents:  25,12,5<hr>456<br>There are 1 agents:  60<hr>352<br>There are 2 agents:  135,453<hr></div>

Open in new window


Live Sample http://jsbin.com/jebupoheja/2/edit?html,js,output

jquery getJson http://api.jquery.com/jQuery.getJSON/
0
RobOwner (Aidellio)Commented:
arrays in JavaScript are objects: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_13138-Javascript-is-just-an-Object.html

So the closest you're going to get is the code below:

http://jsbin.com/yeqele/1/edit?js,console

var locations = {
  "Downtown": [],
  "Midtown": [],
  "Uptown": []
};
locations.Downtown.push("Alex");
locations.Downtown.push("Bob");
locations.Downtown.push("Ray");

locations.Midtown.push("Dave");

locations.Uptown.push("Cleopatra");
locations.Uptown.push("Jessica");

console.log("Downtown length: " + locations.Downtown.length);
console.log("Midtown length: " + locations.Midtown.length);
console.log("Uptown length: " + locations.Uptown.length);

Open in new window

0
Slick812Commented:
greetings  APD_Toronto, , You need to try and do several MANY PHP variables of different types (strings, integers, floats, arrays) and then "transfer" those "variables, and values" to a working Javascript page output in the <script> tags and the JS to HTML output, to see what can and, , can NOT be accomplished with the "String" transitions, and the differences of the arrays (PHP and JS).  as to you last comment where you have -
    loc[0] = 123 //Downtown
        agent[0] = 25 //Which is alex

Since PHP and Javascript are both "scripting" languages, you can use numbered arrays without having consecutive numbers, any numbers in any order can be used. So for your PHP to JS I did this code on a PHP server, and it worked for me. This was in a properly taged page with <head>, <body>, and all the rest needed HTML -
<?php
$loc = array();
$loc[123] = array(25,10,5);
$loc[456] = array(60);
$loc[352] = array(135,453);
$loc[211] = array(35,53,616,82,259,44);
?>
<script>/* <![CDATA[ */
<?php
$jsOut = "var loc = [];\n";
foreach($loc as $key => $val) {
  $jsOut .= 'loc['.$key.'] = [';
  for($i = 0; $i < count($val); ++$i) $jsOut .= $val[$i].',';
  $jsOut = substr($jsOut, 0, -1);
  $jsOut .= "];\n";
  }
echo $jsOut;
?>

document.write("<br />123-1 is= "+loc[123][1]+", , 456-0 is= "+loc[456][0]+", , 211-4 is= "+loc[211][4]);
/* ]]> */</script>

Open in new window


and this was in the HTML source code for the page -
<script>/* <![CDATA[ */
var loc = [];
loc[123] = [25,10,5];
loc[456] = [60];
loc[352] = [135,453];
loc[211] = [35,53,616,82,259,44];

document.write("<br />123-1 is= "+loc[123][1]+", , 456-0 is= "+loc[456][0]+", , 211-4 is= "+loc[211][4]);
/* ]]> */</script>

Open in new window

and the page output was -
        123-1 is= 10, , 456-0 is= 60, , 211-4 is= 259

- - - - - - - - - - -
As in your example, this uses just numbers as array keys and values.
I feel I need to say, that if you try and use user provided Strings as values in the PHP to JS variable conversions, you will get to a point where a PHP string has one of the quotes, and if you try and write out that string with the quotes needed for JS may like -
<?php
echo 'var str1 = "'.$phpString.'";'
?>


Then a double quote will NOT WORK from the PHP string, because the JS string is defined with "
   SO , you will need to escape that double quote in PHP, in order for that string to cooperate in the JS.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
APD TorontoSoftware DeveloperAuthor Commented:
Sorry guys, have been ill for the past 2 days, now I getting back to it.

Just to explain my goal before I go to your examples... In MySQL I have locations table, agents table, and a linked table for a many-to-many relationships. The end result need to be that when the user selects a location, they would get a list of agents without the page refreshing.
0
APD TorontoSoftware DeveloperAuthor Commented:
Thank you
0
Slick812Commented:
@APD_Toronto - hope you get fit, and get well soon.

as to your last post with -  "locations table, agents table, and a linked table for a many-to-many relationships"
Not understanding what this SQL requirements has to do with your question of -
     "Is it possible to have a Jagged Array in JS, and how?"

You have changed the definition of what you may or may not need for your page, more than once, and I have no idea at this point, what you need for your page to work.

Now you say -
    "The end result need to be that when the user selects a location, they would get a list of agents without the page refreshing. "

But this combined with your SQL tables requirement, does not have me thinking of how to help you?

this part - "get a list of agents without the page refreshing", would mean that an AJAX server exchange would be needed, and I guess that there is a <select> somewhere as you say - "user selects a location" ? ?


Can you take some time to review what your web page starts with, as if there is a <select>, or no <select> and use other. And what you need the page to do, and most important to me, what is the HTML format you need to display for your "list of agents" from the SQL select result? What is the Javascript suppose to do as far as your "jagged array" is used, and the server PHP code? And tell us what you are trying to build and how you need it to work?
0
APD TorontoSoftware DeveloperAuthor Commented:
Slick, I just will have a select control with list of locations, so when I populate that I will also build my JS array, and on change I will pass the location id to my JS function. Your example helped me out, that is why I gave you the most points.
0
Slick812Commented:
I was typing my last comment, before the solution was accepted, sorry if it is out of place at this point.
0
APD TorontoSoftware DeveloperAuthor Commented:
no problem
0
Slick812Commented:
be sure to take the time to learn your Javascript, , Web deveolpment now Requires this important factor. tanks 4 points!
0
Ray PaseurCommented:
I agree with what Slick812 says about JavaScript.  If you like books, this is the best I've found.
http://www.amazon.com/JavaScript-Definitive-Guide-Activate-Guides/dp/0596805527

Best regards, ~Ray
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.