This question already has answers here:
Is it possible to create an empty multidimensional array in javascript/jquery?
(8 answers)
Closed 9 years ago.
can any one help me to create and parse a 3d array in javascript.
im having a questionId each question Id have a selected option and an optional option text.
so i need to create a 3d array for questionId,optionId,optionText(string)..
Thnks in advance
A one dimension array would be:
var myArr = new Array();
myArr[0] = "Hi";
myArr[1] = "there";
myArr[2] = "dude";
alert(myArr[1]); // Alerts 'there'
A two dimensional array would be:
var myArr = new Array();
myArr[0] = new Array("Val", "Va");
myArr[1] = new Array("Val", "yo");
myArr[2] = new Array("Val", "Val");
alert(myArr[1][1]); // Alerts 'yo'
A 3D array is more complicated, and you should evaluate your proposed use of it as it has a limited scope within the web. 99% of problems can be solved with 1D or 2D arrays. But a 3D array would be:
var myArr = new Array();
myArr[0] = new Array();
myArr[0][0] = new Array()
myArr[0][0][0] = "Howdy";
myArr[0][0][1] = "pardner";
alert(myArr[0][0][1]); // Alerts 'pardner'
var data = new Array();
data starts off as a regular one-dimensional array. A two dimensional array is really just an array of arrays. So you could do something like
for (var i = 0; i<numberOfQuestions; i++){
data[i] = new Array();
data[i][0] = something;
data[i][1] = somethingElse;
}
Alternatively you could use the following approach
for (var i = 0; i<numberOfQuestions; i++){
data.push([something, somethingElse]);
}
In any case, at some point you are going to need a loop to populate your initial array with sub-arrays to get the 2d effect.
Okay, so as I said in comment to the question, I think you actually need 2D array. That is, if you have N number of questionIds and each questionId has two properties: optionId and optionText
You can create it somehow like this:
var twoD = new Array();
twoD[1] = new Array();
twoD[1]['optionId'] = 3;
twoD[1]['optionText'] = 'blabla';
twoD[2] = new Array();
twoD[2]['optionId'] = 5;
twoD[2]['optionText'] = null;
alert(twoD[1]['optionId']);
Although note that array with associative key is actually an object in JavaScript.
Update: looping through JavaScript
for(var question : twoD){
alert(question['optionId']);
alert(question['optionText']);
}
hi you can create the nth dimension error in javascript one of the example is below
var apple = new Array();
apple[1] = new Array();
apple[1][1] = new Array();
apple[1][1][1] = 'yourname'
now you can use the recursive function to iterate through the array and check and pare every thing.
Related
I just want set 2 arrays which should contain for loop output.
Here's code:
var key_ls = new Array();
var value_ls = new Array();
for (var a in window.localStorage) {
key_ls[a] = a;
value_ls[a] = localStorage[a];
}
and it gives me no result. What do i wrong?
What you're looking for is key_ls.push(a), which will simply add another item to the array. Also use [] instead of new Array().
I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.
This question already has answers here:
is the + operator less performant than StringBuffer.append()
(13 answers)
Closed 9 years ago.
I have two jQuery variables. Each variable is a text string containing words separated by a comma.
var myFirstVariable = green,blue
var mySecondVariable = circle,triangle
I would like to have a third variable retured like this:
var myThirdVariable = greencircle,bluecircle,greentriangle,bluetriangle
The order of the words in myThirdVariable is not important. But my first two variables can contain any number of words, so if
var myFirstVariable = green,blue,yellow
var mySecondVariable = circle,triangle,square
Then I need my third variable to returned like this:
var myThirdVariable = greencircle,bluecircle,yellowcircle,greentriangle,bluetriangle,yellowtriangle,greensquare,bluesquare,yellowsquare
I think I need to push() both variables into an array but I'm struggling with this area of jQuery. Hope someone can shed some light on this. Many thanks.
I'm struggling with this area of jQuery
That's simply because the jQuery library has no tools for this kind of work.
Use the native JavaScript functionality instead, specifically the String split method, the Array join method, the string concatenation operator + and for-loops:
var myFirstVariable = "green,blue"
var mySecondVariable = "circle,triangle";
var firstArr = myFirstVariable.split(","),
secondArr = mySecondVariable.split(","),
thirdArr = [];
for (var i=0; i<firstArr.length; i++)
for (var j=0; j<secondArr.length; j++)
thirdArr.push(firstArr[i]+secondArr[j]);
var myThirdVariable = thirdArr.join(",");
You can use the plain old string split method to get 2 arrays.
http://www.w3schools.com/jsref/jsref_split.asp
You could then use nested for loops to push the new strings into your 3rd array and then use the join method to create the final string.
http://www.w3schools.com/jsref/jsref_join.asp
Try
var myFirstVariable = 'green,blue'
var mySecondVariable = 'circle,triangle'
var myThirdVariable = fn(myFirstVariable, mySecondVariable);
console.log(myThirdVariable)
function fn(fv, sv){
var fa = fv.split(','), sa = sv.split(','), ta = [];
for(var i = 0; i < fa.length; i++){
for(var j = 0; j < sa.length; j++){
ta.push(fa[i] + sa[j])
}
}
return ta.join(',')
}
Demo: Fiddle
OK so you don't need jquery to achieve this, just JavaScript.
check out this answer here to help you:
How to merge two arrays in Javascript and de-duplicate items
I have a very simple JS Arrays question, my simple canvas game has been behaving differently when I replaced one block of code with another. Could you look them over and see why they are functionally different from one another, and maybe provide a suggestion? I may need these arrays to have 20+ items so I'm looking for a more condensed style.
There's this one, which is short enough for me to work with, but doesn't run well:
var srd=new Array(1,1,1);
var sw=new Array(0,0,0);
var sang=new Array(0,0,0);
var sHealth=new Array(20,20,20);
And then there's the original one, which is longer but works fine:
var srd = new Array();
srd[1] = 1;
srd[2] = 1;
srd[3] = 1;
var sw = new Array();
sw[1] =0;
sw[2] =0;
sw[3] =0;
var sang = new Array();
sang[1] = 0;
sang[2] = 0;
sang[3] = 0;
var sHealth = new Array();
sHealth[1] = 20;
sHealth[2] = 20;
sHealth[3] = 20;
Arrays are zero-indexed in JavaScript. The first element is 0, not 1:
var srd = new Array();
srd[0] = 1;
srd[1] = 1;
srd[2] = 1;
Also, you may want to use the more common array constructor:
var srd = [1, 1, 1];
I have a feeling that you may be assuming that the first element is 1 instead of 0, which is why the first version doesn't work while the second one does.
You should do this....in Arrays values are stored as such that first one is at 0 and so on.
so 1st value will be accessed as this...
var x = abc[0]; //first value of array abc being assigned to x.
Do this (you see i actually read your question and this is what you like)
var srd=['',1,1,1];
var sw=['',0,0,0];
var sang=['',0,0,0];
var sHealth=['',20,20,20];
you can declare an array(object) in javascript like this
var x = []; -------------Literal - its a shortcut provided by JS to quickly declare something as an Array.
var x = new Array; --Array constructor
Things to look up regarding
literal
object literal
proto
word new
function object
function property prototype
You can also do these:
var x=1,y=2,
z=3,
f;
var b = something || {}; \\become a copy of object called something if it's not there then become an empty object.
It looks like one starts the arrays at index 0 and the other one starts at index 1
It depends on your implementation, but it's likely because of arrays being 0-indexed. In your first block of code, each number is offset by one index spot from the second block. The first one is equivalent to:
var srd = new Array();
srd[0] = 1;
srd[1] = 1;
srd[2] = 1;
in the way you wrote it for the second block.
i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)