I'm working on Google Script and I'm testing different ways to create two dimensions arrays.
I have created an array like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0][0]="x";
codes[0][1]="x";
codes[0][2]="x";
codes[0][3]="x";
codes[1][0]="x";
codes[1][1]="x";
codes[1][2]="x";
codes[1][3]="x";
codes[2][0]="x";
codes[2][1]="x";
codes[2][2]="x";
codes[2][3]="x";
codes[3][0]="x";
codes[3][1]="x";
codes[3][2]="x";
codes[3][3]="x";
codes[4][0]="x";
codes[4][1]="x";
codes[4][2]="x";
codes[4][3]="x";
codes[5][0]="x";
codes[5][1]="x";
codes[5][2]="x";
codes[5][3]="x";
And it is working fine.
I read following links here, here and here.
But when I do it like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
It didn't work, so I tried like this:
var codes = new Array([["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"]]);
it didn't work either.
When the code don't work, I get no error, just no display of the values.
What am I doing wrong? It looks to be the same code and the two not working ways are recommended in many documentations.
W3schools says that there is no need to use new Array().
For simplicity, readability and execution speed, use literal method ex:
var animals = ["cat", "rabbit"];
Reason why your code was not working is that you're equaling codes inside the loop and after end of loop scope 'codes' is getting only the last set array. Instead you should push those arrays to codes.
var codes = [];
for (var i = 0; i < 6; i++) {
codes.push([i]);
}
console.log(codes)
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
Better yet, two for loops to create the double array:
var codes = [], // Initiate as array, in Javascript this is actually fastre than using new (I don't know any cases you should use new)
rows = 6,
columns = 6;
for (var i = 0; i < rows; i++){
codes.push([]); // Initiate
for (var j = 0; j < columns; j++){
codes[i][j] = 'x';
}
}
Other idea, pre-initiate an array with the correct columns then copy:
var arrTemp = [],
codes = [],
rows = 6,
columns = 6;
for (var j = 0; j < columns; j++)
arrTemp[i] = 'x';
for (var i = 0; i < rows; i++)
codes.push( arrTemp.slice(0) ); // If you just push the array without slice it will make a reference to it, not copy
Other way to pre-initiate the array with 'x's:
arrTemp = Array.apply(null, Array(columns)).map(function () {return 'x'});
Related
Bit of a theoretical question, if I had a JavaScript application where I have multiple Players and for each player there will be 100 computer generated maths questions.
In single player mode it's easy, just generating the questions for the one player:
var player1Qs = [];
for (i = 0; i < maxQustions; i++) {
// Generate Question Object
var question = {};
...
// Add to Array
player1Qs.push(question);
}
That works with no issue. However, when I add a second player into the mix using the same sort of idea as above is where I get a bit puzzled. I'm tryinng to do it without using a multi-dimensional array becasue I'm trying to keep it as simple as possible, but it might be unavoidable.
So player 2 would look something similar to this:
var player1Qs = [];
var player2Qs = [];
for (i = 0; i < playerCount; i++) {
for (j = 0; j < maxQustions; j++) {
// Generate Question Object
var question = {};
...
// Add to Array
???
}
}
Would there be a way of me adding to those two arrays dynamically using a for loop? Or would I need a containing array of players and inside that an array for the questions?
Something like this should do the trick:
// Make sure all players exist.
var players = [];
for (var i = 0; i < playerCount; i++) {
players.push({ name: "Player " + i, questions: [] });
}
// Create questions
for (var i = 0; i < maxQuestions; i++) {
// Generate Question Object
var question = {};
// Do stuff with this question
// Assign the current question to all players.
for (var j = 0; j < playerCount; j++) {
players[j].questions.push(question);
}
}
I'm tryinng to do it without using a multi-dimensional array becasue I'm trying to keep it as simple as possible
I would argue that having a two-dimentional array is the simplest use-case, as you suggest in your question:
Or would I need a containing array of players and inside that an array
for the questions?
The answer is yes (at least if you want to keep it simple). The players array will keep all the players, and each player can then have 100 questions each.
var maxQustions = 100;
var players= []
var player1Qs = [];
var player2Qs = [];
players.push(player1Qs);
players.push(player2Qs);
for (i = 0; i < players.length; i++) {
for (j = 0; j < maxQustions; j++) {
var question = {};
players[i].push(question);
}
}
follow this approach, I assume you have dynamic players and its array:-
var data = {};
var player = [1,2]
var c = [1,2,3,4,5]
for(j=0;j<player.length;j++)
{
data['players'] = player;
data['questions'] = c
}
console.log(data)
I've to do a strange thing and I don't know if is possible.
Let assume I've one aray
MasterArray = [1,2,3,4];
Now for each MasterArray item I need to have multiple insertion, for example under the item 1 I've to push N value, for example the MasterArray[0] must have this correlations
5,8,3,9 ...
This for any items on MasterArray.
My first idea is to create a new array one for each MasterArray items, something like this
var newobject = X;
for (i = 0; i < MasterArray.length; i++) {
Arr[i] = push the newobject ;
}
But I don't think that is a good way!
The purpose it to have a kind of correlated array.
MasterArray[0] is correlated to another array [5,8,3,9, ...]
MasterArray[1] is correlated to another array [5,6,7,1, ...]
MasterArray[2] is correlated to another array [7,45,23,2, ...]
And so on
I hope to have explained myself
Just create a 2D array in this way:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = new Array(10);
}
Or, if you don't need to specify any size:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = [];
}
EDIT:
For manipulate you just need to use innested loops:
for (var i = 0; i < myArray.length; i++) {
for (var j = 0; i < myArray[i].length; j++) {
myArray[i][j] = x; // where x is some variable
}
For add elements in the back just use .push() method:
myArray[0].push(5);
I want to initialize and then print the elements of a 2D array using javascript.
I wrote this code but nothing displays as output. How to output this array?
var m = 6;
var n = 3;
var mat = new Array[m][n];
for (i = 0; i < mat.length; i++) {
for (j = 0; j < mat[i].length; j++) {
mat[i][j]) = i * j;
document.writeln(mat[i][j]);
}
document.writeln("<br />");
}
<html>
<body>
</body>
<script>
var m=6;
var n=3;
var mat =new Array(m);
for( var i=0; i < m ; i++){
mat[i] = new Array(n);
for( var j=0;j< n ;j++){
mat[i][j] = i*j;
document.writeln(mat[i][j]);
}
document.writeln("<br />");
}
</script>
</html>
As BenG pointed out, you've got an extra ) but you also aren't initializing your array correctly. Javascript doesn't allow you to declare multi-dimensional arrays like other languages. Instead, you'd have to do something more like this:
var m = 6;
var n = 3;
var mat = new Array(m);
for (var i = 0; i < m; i++) {
mat[i] = new Array(n);
}
Javascript arrays are dynamic. They will grow to the size you require. You can call push() to add a new element to the array. It's also worth noting that you should avoid using the new keyword with objects and arrays. Use their literal notations [] for arrays and {} for objects. So a better solution here would be to push to the arrays as you need them.
var mat = [];
var m = 6;
var n = 3;
for (var i = 0; i < m; i++) {
// Let's add an empty array to our main array
mat.push([]);
for (var j = 0; j < n; j++) {
mat[i].push(i * j);
document.writeln(i * j);
}
document.writeln('<br />');
}
Hello there am trying to save news tweets into three different array which are dynamically created.
am finding trouble when i want to get the text from each one of those array and make another request to twitter.
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
news_array[i] = [{user:user,date:date,profile_img:profile_img,text:text,url:url}];
}
for (var i = 0; i < news_array.length; i++) {
for (var x=0; x<i.length; x++){
console.log(news_array[i][x].user);
}
}
});
}
It doesn't show anything on the console.log.
thanks for the help!!!!!
First, make sure that your count is smaller than the data array's length, otherwise this could lead to some undefined values:
for (var i = 0; i < count && i < data.length; i++) …
Then, why are you creating all those one-element-arrays in the news_array? Just use only objects.
This would solve your actual issue: You are looping wrong over those inner arrays. The correct code would be
for (var i = 0; i < news_array.length; i++) {
for (var x = 0; x < news_array[i].length; x++){
console.log(news_array[i][x].user);
}
}
Also, you should indent your code properly. You have some odd braces around, which don't make the code readable.
The problem is the x<i.length in the for loop near the end. i is a number, so it doesn't have a length. You probably meant x < news_array[i].length.
You may try the following:
Use the push method to append elements / data in your array new_array
Use only 1 loop for to display the user value on console
So your code will be something like this:
news_tweets("reuters","1652541",3);
function news_tweets(query, user_id,count) {
news_array = [];
$.getJSON("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=false&user_id=" + user_id + "&count="+count+
"&callback=?",
function (data) {
for (var i = 0; i < count; i++) {
var user = data[i].user.name;
var date = data[i].created_at;
var profile_img = data[i].user.profile_image_url;
var text = data[i].text;
var url = (data[i].entities.urls.length > 0 ? data[i].entities.urls[0].url : '');
// Pushing your elements in your array, 1 by 1
news_array.push({user:user,date:date,profile_img:profile_img,text:text,url:url});
}
// Here you only need 1 loop!
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i][x].user);
}
});
}
First thing is i would loop the first one till data.length rather than count because its an api and it "might" or "might not" return all the data. So it will be fool proof to loop till data.length
And your problem is with i.length
for (var i = 0; i < news_array.length; i++) {
console.log(news_array[i].user);
}
this should work. not sure why you had to loop through a loop.
function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed