pushing new array into a 2d array - javascript

I'm trying to push a new array into a global array here:
var history = [ ];
function addHistory(array)
{
history.push(array);
console.log(history)//to check what is the value of array
}
var test1 = [0,0,0,0,0];
var test2 = [1,1,1,1,1];
addHistory(test1);
addHistory(test2);
After doing like this, the array should be:
[ [0,0,0,0,0] , [1,1,1,1,1] ]
But instead it prints
[ [1,1,1,1,1] , [1,1,1,1,1] ]
So basically it replaces all old arrays in array "history", instead of pushing it at the end.
What can be wrong here?
Thanks a lot
EDIT:
Sorry, forgot to mention that my actual variable is not called history (I called it that way just that you can imagine what I want). It is called "rollHist"

history is a protected term in javascript. Changing it to this will fix it:
var myHistory = [];
function addHistory(array)
{
myHistory.push(array);
console.log(myHistory)//to check what is the value of array
}
var test1 = [0,0,0,0,0];
var test2 = [1,1,1,1,1];
addHistory(test1);
addHistory(test2);
You can read more about the various protected words here

Related

Setting the value of a multidimensional object or array property in Javascript

Yes I know how to loop through arrays (types) in Javascript. The fact is, I'd like to know how to set a multiDimensionalArray array's value by a set of given indexes to keep it as generic as possible. For example I've an array with a length of 3 (which could as well be a length of 4, 100, ...):
var indexes = [0, "title", "value"];
I know the multidimensional array (mArray) can be set by putting the indexes like so:
multiDimensionalArray[0]["title"]["value"] = "Jeroen"; or multiDimensionalArray[indexes[0]][indexes[1]][indexes[2]] = "Jeroen";
The fact that the given indexes array can vary and does not always contain the same index names so I'm search for a solution like this:
multiDimensionalArray[indexes] = "Jeroen";
I don't know how to code the assignation if this. I've searched on Google/Stack Overflow. Maybe I'm using the wrong keywords. Can anyone help me?
Thanks!
Following example is how I've made it working thanks to Jonas's example:
var json = [{
"hello": {
"world": 1,
"world2": 2
},
"bye": {
"world": 1,
"world2": 2
}
}];
var indexes = [0, "hello", "world2"];
var value = "value";
indexes.slice(0,-1).reduce((obj, index) => obj[index], json)[indexes.pop()] = value;
console.log(json);
So imagine you have a structure like this:
var array=[[["before"]]];
Then you want
var indexes=[0,0,0];
var value="value";
to actually do:
array[0][0][0]="value";
which can be easily achieved with reduce:
indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
Explanation:
indexes.slice(0,-1) //take all except the last keys and
.reduce((obj,index)=>obj[index] //reduce them to the resulting inner object e.g. [0,0] => ["before"]
,array) //start the reduction with our main array
[indexes.pop()]=value;// set the reduced array key to the value
var array=[[[0]]];
var indexes=[0,0,0];
var value="value";
indexes.slice(0,-1).reduce((obj,index)=>obj[index],array)[indexes.pop()]=value;
console.log(array);

variable values to store a array

how can I variable values to store a array?
Look my code:
var collection =normal,user,student ;
var array = [collection];
alert(array[0]);
In this case, alert would popup a normal,user,student. but i need an array such as array[0] get normal,array[1] get user,array[2] get student like that
how it is possible
Is there any chance to convert such variable into a JS array?
As normal,user,student are values. You can use split() to split the string using , as deliminator then indexes can be used to access elements.
var collection = "normal,user,student";
var array = collection.split(',');
console.log(array[0]);
There are many, many ways to create arrays ... some examples:
// just declare an array directly
var array1 = ["normal", "user", "student"];
console.log(array1[0]);
// use split to create an array out of a string
var collection = "normal,user,student";
var array2 = collection.split(",");
console.log(array2[1]);
// use split and map to create an array by your needs
var collection = " normal, user , student ";
var array3 = collection.split(",").map(function(value) {
return value.trim();
});
console.log(array3[2]);
// push each value to the array
var array4 = [];
array4.push("normal");
array4.push("user");
array4.push("student");
console.log(array4[0]);
// ...
var collection = "normal,user,student";
var jsarray = collection.split(",");
alert(jsarray[0]);
alert(jsarray[1]);
alert(jsarray[2]);
Are you trying to add the existing variables to the array? If so you are just missing your square brackets:
var collection = [normal, user, student];
If you would like the elements to contain the string values, you would do it like this:
var collection = ["normal", "user", "student"];

How to create object of array in Javascript

I want to create the object of list that looks like this:
myObj = {"foo":[1,2,3,4],
"bar":[3,5,7,8]}
I tried this but failed
var myObj = new Object();
myObj["foo"].push(1)
myObj["foo"].push(2)
#...etc
What's the right way to do it?
You need to create the array first
myObj["foo"] = []
then call your push method
It depends, are you trying to reassign the myObj attribute foo with a completely new array? Or are you trying to append to the already existing array?
In the former case:
myObj.foo = [1,5,6,4] // new array
And in the latter:
myObj.foo.concat(/*new numbers*/)
The {} notation is commonly used.
var myObj = {};
myObj.foo = [];
myObj.bar = [];
Later you can manipulate the arrays.
myObj.bar.push('elem1');
myObj.bar.pop();
// ...
First you should declare the properties of the object as array in order not to get some unpleasent situations.So you can use new Object to create an object like this.
var myObj=new Object;
and define properties as empty arrays
myobj.prop1=[];
myObj.prop2=[];
then you can push whatever you want into prop1 or prop2 by simply reaching them inside the object as
myObj.prop1.push(someData)
OR
You can use a better way to declare this object like below
var myObj={
prop1:[],
prop2:[]
}
And again you can push whatever you like into them as i told above
as myObj.prop1.push(data)
Try first declare your object, so your second line goes first
var myObj = new Object();
then you fill your object with data
myObj = {"foo":[1,2,3,4],"bar":[3,5,7,8]}
then the rest of your code should work fine
myObj["foo"].push(1)
myObj["foo"].push(2)
result [ 1, 2, 3, 4, 1, 2 ]

Javascript: Accessing properties on multidimensional array

I have an array that loads an array with properties at a certain index:
var hotspotLocationsTextAndAudio [];
var myArr = [
[{x:10, y:40, filename:"test", text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"}]
];
hotspotLocationsTextAndAudio[window.IDNum] = myArr;
To access a property at a certain index of hotspotLocationsTextAndAudio (my case being what window.IDNum equals) at an index of the array inside that (0) and a certain property, I thought I just needed to do the following:
alert(hotspotLocationsTextAndAudio[window.IDNum][0].x);
That returns undefined.
Assuming the code you're actually using is this:
var hotspotLocationsTextAndAudio [];
var myArr = [
[{x:10, y:40, filename:"test", text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"]}
];
hotspotLocationsTextAndAudio[window.IDNum] = myArr;
The alert code you'll need is:
alert(hotspotLocationsTextAndAudio[window.IDNum][0][0].x);
The reason being that you wrapped your objects in [], putting them in an array.
Or, in order to have your original alert working, you'll need to change myArr to this:
var myArr = [
{x:10, y:40, filename:"test", text:"test"},
{x:50, y:60, filename:"test2", text:"test2"}
];
This works for me: http://jsfiddle.net/Ku2tQ/
var hotspotLocationsTextAndAudio = [];
var myArr = [
[{x:10, y:40, filename:"test", text:"test"}],
[{x:50, y:60, filename:"test2", text:"test2"}]
];
alert(myArr[1][0].x);
First of all hotspotLocationsTextAndAudio is an empty array, and you never push/merge myArr to it. So trying to access a nested value of an empty array, will fail.
arr, is also never defined.
If possible, keep it simple and try avoiding nested array with too much deep.

How to create object inside object in Javascript

I am trying to create an object - that each parameter inside it is another object:
var divTextPerScreenWidthMap = new Object(
{'360','click'},
{'480','click it'},
{'768','click it right'},
{'1024','you know you want to click it'},
{'1280','click this button which is very long will help you'}
);
This is not working since I am getting an error. how do I need to write it to make it work? Should I change the outer object into an Array and how?
You have syntactical errors.
First of all object literal follows the syntax below:
var literal = {
"Name": "value",
"Array": [],
"NestedObject": {}
};
Name value separator is the colon, not comma.
EDIT
The above code might be rewritten as follows
// declaration via array initializer
var myArray = [
// name : value syntax
{'360': 'click'},
// values separated by comma
{'480': 'click it'},
{'768': 'click it right'},
{'1024': 'you know you want to click it'},
{'1280': 'click this button which is very long will help you'}
]
however at this point you cannot access your objects via i'ts names like this:
var firstObject = myArray[0];
// will throw an error
firstObject.360 = "not click";
You can only use it as follows
firstObject["360"] = "not click";
Hence I suggest you to name the properties according to variable naming rules.
In javascript object is a simple map. It is better to use literal {} instead od new Object();
var myObj = {
prop : {},
prop2 : {}
}
Don't create an Object via its constructor, use the literal syntax {}.
Also, objects have keys and properties. Your objects seem to only have values. Did you mean to use Arrays?
You completely forgot to give keys for your values. If you don't want to use keys, use arrays:
var divFoo = [
[360, "click"],
[480, "click it"] // et cetera
];
This would give you an array of arrays. For instance, divFoo[0][0] == 360
If you want keys, use an object:
var divFoo = {
"360": "click",
"480": "click" // et cetera
}
This gives you simple object. divFoo[360] == "click"
Or you could use an array of objects for more descriptiveness:
var divFoo = [
{time: 360, text: "click"},
{time: 480, text: "click it"} // et cetera
];
In this case, divFoo[1].text == "click it".
Also, a few hints:
Don't use new Object or new Array. They're redundant.
There's no need to quote integers if they're used as values.
It would make sense to represent your collection of objects as an array:
var divTextPerScreenWidthMap = [
{360:'click'},
{480:'click it'},
{768:'click it right'},
{1024:'you know you want to click it'},
{1280:'click this button which is very long will help you'}
];
//You could iterate over your array of objects with a for loop:
var i, value;
for (i=0; i < divTextPerScreenWidthMap.length; i++) {
value = divTextPerScreenWidthMap[i];
console.log(value);
};
//Alternatively, you could represent your data structure as one object:
var divTextPerScreenWidthMap = {
360:'click',
480:'click it',
768:'click it right',
1024:'you know you want to click it',
1280:'click this button which is very long will help you'
};
//So now if you have a screen width, you can quickly get back the corresponding message:
var screenWdith = 360;
alert(divTextPerScreenWidthMap[screenWidth]);
You can also created nested objects like this:
let obj1 = {};
obj1['title'] = 'Vehicles';
let obj2 = {};
obj2['name'] = 'Honda City';
obj1['cars'] = obj2;
console.log(obj1);
Create a method in object, create a new object in that method and return it.
const obj = {
one: "one is just a property",
two: function(){
const newObject = {
three: "now two will return new a new object"
}
return two;
}
}

Categories