Studious Amateur
Studious Amateur

Reputation: 1

Javascript: Varying width multi dimension array

I want to create a 2D array, with varying width. I have initialized the outer array as I know the number of rows.

var listofcities = new Array(lengthofcites); //i get this lengthofcitles from another routine

Now, I will get the list of facilities in the cities from another routine as list. E.g. listoffacilities = ["water","air"] for a city. For another city I will get this list as listoffacilities = ["water","air","electricity"].

I should be able to store this in my outer array in such a way that

listofcities[0] = ["water","air"]
listofcities[1] = ["water","air","electricity"]

I'm not able to use the push function like listofcities[0].push(listoffacilities) in the inner loop.

All the examples I could see from web have same sized rows/columns.

Upvotes: 0

Views: 302

Answers (2)

Barmar
Barmar

Reputation: 782498

You shouldn't be pushing onto a specific element of listofcities, just push onto the array itself:

var listofcities = []; // don't specify the length here
listoffacilities = ["water", "air"];
listofcities.push(listoffacilities);
listoffacilities = ["water","air","electricity"];
listofcities.push(listoffacilities);
console.log(listofcities);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075567

JavaScript doesn't have multi-dimensional arrays; it has arrays of arrays. So multi-dimensional arrays are inherently jagged (the term for when not all subordinate arrays are of the same length).

You do it literally as you've shown:

var listofcities = []; // No need to pre-allocate length
listofcities[0] = ["water","air"];
listofcities[1] = ["water","air","electricity"];
console.log(listofcities);
.as-console-wrapper {
  max-height: 100% !important;
}

This:

var listofcities = [];

creates an empty outer array, and then these:

listofcities[0] = ["water","air"];
listofcities[1] = ["water","air","electricity"];

create subordinate arrays (e.g., ["water","air"]) and store them in that outer array. [...] is an array initializer (often called an "array literal") that creates an array with the items between the brackets.

Here's an example using push; note that you call push on the array (listofcities.push(...)), not an an entry in that array (listofcities[0].push(...)). But once you've put a subordinate array in as an entry, you can push to that subordinate array (listofcities[0].push(...)).

var listofcities = []; // No need to pre-allocate length
listofcities.push(["water","air"]);
listofcities.push(["water","air","electricity"]);
console.log(listofcities);
.as-console-wrapper {
  max-height: 100% !important;
}

Upvotes: 2

Related Questions