Make a 2d array with 2 simple array in javascript - javascript

I've been searching for hours for an error in my javascript's code but I really don't understand why this error occur.
So I have 2 array that I've get by using ajax and I want to merge them into an 2d array but this error happen :
Uncaught TypeError: Cannot set property '0' of undefined
So this is my code :
var arrayCityAccident = new Array([]);
for(var i = 0; i < responseAccident.length; i++)
{
arrayCityAccident [i][0] = responseCity[i]['city'];
arrayCityAccident [i][1] = responseAccident[i];
}
I've look up to see if my both 1d array have values and yes they have values so if someone could help me it will help me a lot.
Thank you in advance !

You need to add a new array to arrayCityAccident for each index i:
var arrayCityAccident = [];
for(var i = 0; i < responseAccident.length; i++)
{
arrayCityAccident.push([responseCity[i]['city'], responseAccident[i]]);
}

Well, as soon as i becomes bigger than 0 in your loop, arrayCityAccident[i] doesn't return an array anymore. You only defined arrayCityAccident[0], so accessing arrayCityAccident[i][0] isn't possible.
Just add another array to arrayCityAccident before defining its elements:
var arrayCityAccident = new Array([]);
for(var i = 0; i < responseAccident.length; i++)
{
arrayCityAccident[i] = []; // add a new array to arrayAccident
arrayCityAccident[i][0] = responseCity[i]['city']; // now you can set those properties
arrayCityAccident[i][1] = responseAccident[i]; // without problems
}

Related

Populate specific array indices from other array in JavaScript

I have 2 arrays, arr1 and arr2. They're both 2-dimensional. I want to copy certain array values from arr1 to arr2.
For instance, I want to copy the value from arr1[9][9] into arr2[0][0]. My guess was to write arr2[0][0] = arr1[9][9]; but that failed.
I looked at some similar questions on this site but they did not answer my question.
Here is the code for the particular situation. The code is written is Google Apps script.
// eplList and attList are both arrays. They are filled below (I checked, the values exist)
var eplList = epl.getRange(2, 2, eplLastRow, 2).getValues();
var attList = attsheet.getRange(3, 1, attLastRow, 20).getValues();
var eplListLength = eplList.filter(String).length;
var attListLength = attList.filter(String).length;
// Declaring the empty array I want to fill
var masterArray = [];
var ix, jx, day;
// Here I begin to fill the array
for (ix = 0; ix < eplListLength; ix++)
{
masterArray[ix][0] = eplList[ix][0]; // This is where I am getting the error message
masterArray[ix][1] = eplList[ix][1];
for (jx = 0; jx < attListLength; jx++)
{
if (eplList[ix][0] == attList[jx][day*4-4])
masterArray[ix][6+day] = masterArray[ix][6+day].concat(" ", attList[jx][day*4-2], ": ",attList[jx][day*4-3]);
};
// and some morecode
};
The error I'm getting is "TypeError: Cannot set property '0' of undefined"
To fix particular issue you've got try this code, but i not sure about code below):
masterArray[ix] = [eplList[ix][0], eplList[ix][1]]; // This is where I am getting the error message

Angularjs reports "Cannot set property of undefined"

I'm getting an error that says "cannot set property of undefined".
vm.dtr1 = {}; // maybe I'm initializing this wrong ?
vm.dtr1.date1 = {}; // maybe I'm initializing this wrong ?
for(var x=0; x<5; x++){
vm.dtr1[x].date1 = new Date(days[x]); //getting undefined value
}
vm.dtr is an object, but you are trying to use it as an array by accessing the index. Which will obviously undefined.
You need to declare vm.dtr as an array of type dtx.
You need to change it to be an array, then before assigning a property it must be initialized.
vm.dtr1 = []; // make it an array
for(var x=0; x<5; x++) {
vm.dtr1[x] = {}; // initialize it first
vm.dtr1[x].date1 = new Date(days[x]);
}
Or in better way
vm.dtr1 = [];
for(var x=0; x<5; x++) {
vm.dtr1[x] = { date1: new Date(days[x])};
}
Try following changes will suely work
vm.dtr1 = []; // change here
//vm.dtr1.date1 = {}; // remove this
for(var x=0; x<5; x++){
vm.dtr1[x] ={}
vm.dtr1[x].date1 = new Date(days[x]); //
}
The problem is that the possible values of x are not correct keys for vm.dtr1.
You may want to use for...in loop instead:
for(var x in vm.dtr1) {
if (vm.dtr1.hasOwnProperty(x)) {
vm.dtr1[x] = new Date(days[x]);
}
}
I still don't know what days is. So, you need to figure that out. For more details about iterating over an object, see this post.
I think you might need to do it like this
var vm = {}; vm.dtr1 = [];
var day = ['7/7/2012','7/7/2012','7/7/2012','7/7/2012','7/7/2012']
vm.dtr1[x] = {};
vm.dtr1[x].date1 = new Date(days[x]);
}
Still don't know what days is, i did is as expected input for Date constructor

Google scripts. TypeError: Cannot call method "replace" of undefined

First post please go easy on me.
I have an array that looks something like this [BTC-LTC, BTC-DOGE, BTC-VTC] I am trying to change all the "-" with "_". But am having trouble with using the .replace() method. Here is my code.
var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
var str = JSON.stringify(array[i]);
var res = str.replace("-","_");
fixedArray.push(res);
};
I tried without using the JSON.stringify but that didn't work either. I have also tried to first create var str = String(); this also did not work. Is it possible that the method .replace() is not available in google scripts?
In your example var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
should be
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
However I gather from the comments that this is just a typo in your initial example.
var str = JSON.stringify(array[i]); is redundant. You can just do var str = array[i]; Since the value in the array is already a string, there's no need to turn it into one again - the "stringify" method expects to be given an object or array to work on.
However the main problem is that your for loop goes on one too many iterations. Arrays are zero-based, so you need to stop looping when the index is 1 less than the length of the array, not equal to it. e.g. if array.length is 10 then there are 10 indices, but they start at 0, so the indices are 0,1,2,3,4,5,6,7,8,9. If your loop goes on to equal to array.length, then on the last loop array[10] will be out of bounds, and it's only this last iteration which is giving you the undefined error.
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
var fixedArray = [];
for (var i = 0; i < array.length; i++) {
var str = array[i];
var res = str.replace("-","_");
fixedArray.push(res);
}
If I understood correctly, you're trying to edit strings, not variables, so you need quotes in your array, and a g in your replace in case you have multiple things to replace :
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
fixedArray.push(array[i].replace(/-/g, '_'));
};
code is working fine if we change as below:
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];

cannot iterate through array and change value in JS

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.

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

Categories