push values into an array dynamically with javascript - 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' ]

Related

How to create custom arrays using javascript

I am trying to create an array in the following format:
// Required JSON format to create javascript dynamically
[{id:0,[{'val':1,'bool':true},{'val':2,'bool':true}]}]
I tried using the javascript push method as follows:
var arr2 = [];
var arr3 = arr2.push({'id':0,'value':1,'bool':true});
But this is not giving the desired format. I don't know how to group by a common id. Anyone knows please help me.
Because it isn't a valid object, your array of { val:..,'bool': .. } needs a key. Like so:
var ob = { id: 0,
meaningfulName: [
{'val':1,'bool':true},
{'val':2,'bool':true}
]};
Also having object keys of 'val' and 'bool' aren't very meaningful, choose a name that represents what they are.

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

How to make an array from JSON?

Couldn't think of better title.
Important to note: I'm new to js and I guess its the reason I can't figure it out by myself.
I have a JSON array returned from a database, the JSON array represent a set of points.
Example of the JSON array:
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...]
I want to make a different array whose elements will be a function and the variables of the function will be the elements from the JSON array, like so:
var coordinates = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(1, 3),
new google.maps.LatLng(2, 3),
....
];
I made a function using forEach that counts the elements of the JSON array (for learning and trying to find a way to what I want) but I cant think of a way make the array mentioned above.
You could use Array map method:
var coordinates = JSON_array.map(function(coordinate) {
return new google.maps.LatLng(coordinate.lat, coordinate.lng);
})
This method gives you an new array based on (1) the original array and (2) how you deal with each element. Here's more detailed doc for the method.
you can also use regular for loop
coordinates = [];
for(var i=0;i<JSON_array.length;i++){
coordinates.push(new google.maps.LatLng(JSON_array[i].lat,JSON_array[i].lng));
}
For mapping element from one array to another you can use Array.prototype.map function like
var JSON_array = [{lat:1,lng:2}, {lat:1,lng:3},{lat:2,lng:3}...];
var coordinates = JSON_array.map(function(el){ return new google.maps.LatLng(el.lat, el.lng)});
As Grundy commented you can just do:
coordinates = JSON_array.map(function(x) {
return new google.maps.LatLng(x.lat, x.lng);
});
You might want to get your nomenclature straight though, this has nothing to do with JSON.

How Do I Make an Array of Objects a Reactive Data Source?

I have an array of objects. Say
var
sidelist = [
{
name:"asdf",
id:1234,
types:[...]
}
];
Every object is turned into a box on the page using this construct
Template.global.side = function(){
var obj = [], m;
m = 1;
for (var i in sides){
obj.push({
index : m,
object : sides[i]
});
}
return obj;
}
The HTML:
{{#each side}}
<div class="span{{this.index}}" id={{this.object.id}}>
<div class="side-head">{{this.object.name}}</div>
</template>
There is a function that creates and pushes a new object into the array. How do I make the row of boxes reactively update on the page when the array they depend on changes?
So when I add a new object a new box should appear.
If you want to use Dependencies, it can look like this:
var sidelist = ...;
var sidelist_dep = new Deps.Dependency;
Template.global.side = function(){
sidelist_dep.depend();
// Do your stuff here;
return ...;
};
// Important: call this every time you change sidelist,
// AFTER the change is made.
sidelist_dep.changed();
See: http://docs.meteor.com/#deps
In almost all cases, you should put the objects in a Meteor Collection instead of an array that is part of a reactive object. There are many reasons for this, including the following
Adding, removing, searching, and updating will all be faster
The reactivity will be on the element level instead of the array
Meteor won't re-render the whole set of objects when something is added or deleted - just the change
You can define a sort order on the collection, making it much more flexible than a fixed sequence
Take a look at Andrew Wilcox's isolate-value smart package:
https://atmosphere.meteor.com/package/isolate-value
The README contains the exact example of selectively rerendering relevant templates when values are added/removed from an array stored in a Session varaible.

Array within an array

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"]
];

Categories