Array within an array - javascript

I believe that what I'm trying to do is declare several arrays within an array.
In a text document, I have the following:
"一","いち","one"
"二","に","two"
"三","さん","three"
"四","し・よん","four"
"五","ご","five"
Which I want to automatically place into an array with the items assigned as groups of 3, so for instance set_one[0][1] would be "いち", set_one[3][2] would be "four", so on.
For the life of me, I cannot figure out how to even read the values line by line from the plain text document, let alone try to automatically assign them into arrays.. so I tried manually. I have:
var set_one = new Array(new Array("一", "いち","one"), new Array("二", "に","two", new Array("三", "さん","three", new Array("四", "よん・し","four", new Array("五", "ご","five");
Which, when document.write(set_one[3][2]); is called, nothing happens what-so-ever.. I even tried a for loop to see if anything exists in the (set_one) array at all, though as far as I can tell, nothing does.
It's difficult working on this windows machine to say the least, as I have no debugging tools available, and it doesn't have an active Internet connection! What am I doing wrong? Is there a better way of doing this? Is it even possible to read the values into an array automatically line-by-line, then assign the values to individual arrays based on the comma values?

You're not creating the array correctly. For example, when you have:
new Array("二", "に","two", new Array("三", "さん","three"))
You are actually creating a single-element array, in which the 3rd position is itself another array. Either use:
new Array (new Array("二", "に","two"), new Array("三", "さん","three"))
Or the much simpler, and less confusing way of creating arrays in JavaScript:
var set_one = [
[ "一","いち","one" ],
[ "二","に","two" ],
[ "三","さん","three" ],
[ "四","し・よん","four" ],
[ "五","ご","five" ]
];
set_one[0][1]; // いち

var set_one = [
["一","いち","one"],
["二","に","two"],
["三","さん","three"],
["四","し・よん","four"],
["五","ご","five"]
];

Related

Get a key from an array inside an array in javascript

var Game1 = ["name", "image", "genre"]
var Game2 = ["name2", "image2", "genre2"]
var Game3 = ["name3", "image3", "genre3"]
var games = [Game1, Game2, Game3]
I want to store some arrays inside an other array, as shown above, and I want to be able to show all of the names of the arrays. So here, I would like to get Game1[0], Game2[0] and Game3[0], but I want to get them from the games array.
How would I go about doing this?
I was thinking of using a for loop over games, but I'm not sure how to get the 0th element from the arrays inside the games array.
I'm quite new to javascript, which is why I could not figure this out.
You can access like below.
games[0][0] - will gives you the Game1[0] value
games[1][0] - will gives you the Game2[0] value
games[2][0] - will gives you the Game3[0] value
DEMO

Building a 2D Array in Javascript

I've been trying to build a 2D array in javascript, but not having much success. I'm pulling some data from a DB and I then want to combine some fields into a 2D array in order to use it elsewhere in the code. Ideally what I want to end up with is:
mapLocs = [
['name a','location a',1],
['name b','location b',2],
['name c','location c',3]
]
here is the code I am using to build the mapLocs array:
for(i = 0;i < phtLen;i++){
var x = i + 1;
var myLocs = new Array(myPhotogs[i].phtName,myPhotogs[i].phtLoc,x);
console.log(myLocs);
mapLocs[i] = new Array(myLocs);
}
}
which is pretty much the method that I've gathered from reading similar problems here. The console.log() outputs an array consisting of the three elements I want, but if I try to access mapLocs it doesn't seem to consist of three arrays as I would have expected, but of three elements each of which is made up of the three elements in the myLoc array if that makes sense? So:
console.log(mapLocs[0][0]); // Joe Bloggs, SW1A 1AA, 1
where I was expecting just 'Joe Bloggs' and
console.logs(mapLocs[0][1]); // undefined
What am I doing wrong?
The explicit new Array() constructor does not take an array and make a new array identical to the argument array, but takes a list of arguments that you wish to be contained within the new array. So in the line
mapLocs[i] = new Array(myLocs)
mapLocs[i] is actually being set to
[[Joe Bloggs, SW1A 1AA, 1]]
Instead, you could say
mapLocs[i] = myLocs.slice()
which will clone myLocs and place it at index i in mapLocs, resulting in the output you want.

How to format javascript array with lots of values

In javascript, I am creating an array with some values in it. The list of values is relatively long, and results in the single line of code appearing on two lines on most screens. For example, the line of code is:
var fieldNames = ['firstName', 'lastName', 'phoneNumber', 'emailAddress', 'hotelName', 'roundTrip', 'origin', 'departureDate', 'departureTime', 'returnDate', 'returnTime'];
Is there a preferred way to format this line so it's more readable? Should each value in the array be on its own line?
If the goal is more readable code, then putting each element separately on its own line works well.
For example, as is, if you make a change to an element in the array and commit to git, the whole line will show up as being changed in the diff. It is difficult for others to see exactly which element changed.
If each element is on its own line, and you make a change to an element then commit to git, then only the line with the changed element will show up in the diff. It is then obvious which element was changed.
This is what I usually do:
var fieldNames = [
'firstName', 'lastName', 'phoneNumber', 'emailAddress', 'hotelName',
'roundTrip', 'origin', 'departureDate', 'departureTime', 'returnDate',
'returnTime'
];
This is what I do. This may or may not be a good idea.
At least for me, it helps me to understand where the array starts and stops and what variable it belongs to.
We use require.js in our project and sometimes it happens that a module requires a lot of dependencies so our code looks like this:
require([
module1,
module2,
module3,
module4,
module5,
module6
], function(
module1_obj,
module2_obj,
module3_obj,
module4_obj,
module5_obj,
module6_obj
){
...
});
Because we have to define 2 lists that are really long we format it as a column, 1 item in one line, this way when we delete a dependency we can easily delete it in both columns and see that both have identical count of items.
Clarification: first array in require.js defines dependencies and the second gives an object to use of that dependency that is the reason why there are two.
Benefits of not placing any item in first line
var foo = [ // <-- Not having an element on this line.
1,
2,
3
];
Is that then the array is defined in the same fashion as object is usually:
var bar = {
iAmAProperty: "YAY"
};
And in version control you can clearly see if the content of object/array is edited or the name of the object/array
var fieldNames = ['firstName', 'lastName', 'phoneNumber', 'emailAddress',
'hotelName', 'roundTrip', 'origin', 'departureDate', 'departureTime',
'returnDate', 'returnTime'];

Changing the variables of a class in OOP in javascript

I have defined a function called Node which stores the properties of nodes in a graph data structure. The function is something like this:
function Node(){
...
this.outEdges = [];
this.inEdges = [];
...
}
where the inEdges and outEdges store elements of type Edge which is another function I have defined. During the program these arrays are filled with elements.
At some point in my code I need to reset these two arrays so I write:
nodes[i].outEdges.length = 0;
nodes[i].inEdges.length = 0;
where nodes is an array of elements of type Node and I am accessing an element in a for loop.
The problem is, after setting outEdges and inEdges to 0, I expected them to be [] in the nodes[i] property list. However, when I output nodes[i] into console, the outEdges and inEdges still have the elements in them. The stranger thing is that when I output nodes[i].outEdges to console, it prints [] , which is correct, but clicking on [ ] again opens the list of the elements! I can't really figure out why the nodes[i] variables don't change?
That happens (probably) because the browser prints out the empty array but by the time you check it, it has content again. So when you click to expand the browser shows the actual content.
As you can see the values [1,3,7] were added after the command console.log(o) but they are shown on the screen (even though the length shown is 0).
You're not supposed to set the length field. Just re-initialize them:
nodes[i].outEdges = [];
nodes[i].inEdges = [];
Edit: My bad, setting the length should work. It does work for me on Chrome at least. However, I still think it's safer and better style to re-init.
Just create a new object with the same name
nodes[i].outEdges = new Array();

push values into an array dynamically with javascript

I'm have trouble finding a way to push values into an array dynamically. I have given the following situation:
var get_anchors= new Array('pitzel','mitzel','sizzle')
current_anchor= pics[key].anchor; //has the value 'sizzle'
get_anchors[current_anchor].push(new Array('sizzle2','sizzle3'))
Javascript fails and says get_anchors[current_anchor] is undefined
How can I make get_anchors[current_anchor] work. Or is there a different way to get this done?
The desired result should look like 'pitzel','mitzel','sizzle'['sizzle2','sizzle3]
Based on your comment it looks like you want a hash map instead of an array. You can use an object for this:
var anchors = {
'pitzel': [],
'mitzel': [],
'sizzle': []
};
Then you can do:
anchors[current_anchor].push('sizzle2', 'sizzle3');
or assuming that anchors does not have a property with the value of current_anchor, simply assign a new array:
anchors[current_anchor] = ['fooX', 'fooY'];
Of course you can populate the object dynamically as well. Have a look at Working with Objects for more information.
I'm not sure I understand what you're trying to do, but I think you're trying to insert a few elements after where another occurs. This will do the trick:
var get_anchors = [ 'pitzel', 'mitzel', 'sizzle' ];
current_anchor = get_anchors.indexOf(pics[key].anchor);
get_anchors.splice(current_anchor + 1, 0, 'sizzle2', 'sizzle3');
// get_anchors = [ 'pitzel', 'mitzel', 'sizzle', 'sizzle2', 'sizzle3' ]

Categories