Javascript; nested for-loop not working - javascript

var divs = [];
for (var x = 0; x <= nodeArray.length; x++) {
for (var q = 0; q <= nodeArray.childElementCount; q++) {
divs[x][q] = nodeArray[x].childNodes[q].childNodes[0]
};
};
I need a two dimensional array of the child of every child of a div for multiple divs.
Can't get it to work ;c
Anyone knows if this is even possible with javascript?
Thanks.
Edit:
Thanks guys, it works now! :D
I ended up doing it like this:
var divs = [];
nodeArray.forEach(function(array, index) {
divs[index] = nodeArray[index].children;
});
var imgs = [];
for (var x = 0; x < divs.length; x++) {
imgs[x] = [];
for (var y = 0; y < divs[x].length; y++) {
imgs[x][y] = divs[x][y].childNodes[0];
}
}
Using your feedback it works now! Really really really thanks! ;D

Arrays are 0-indexed, This means that the last element of an array is not at array.length but at array.length - 1.
You'll have to create a new array (sub-array) and then start adding elements to it.
Your code should be like this:
var divs = [];
for (var x = 0; x < nodeArray.length; x++) {
// here ^^^
divs[x] = []; // create a new sub-array (or divs.push([]);)
for (var q = 0; q < nodeArray.childElementCount; q++) {
// here ^^^
divs[x][q] = nodeArray[x].childNodes[q].childNodes[0];
};
};

var divs = [];
for (var x = 0; x <= nodeArray.length; x++) {
divs[x] = [];
for (var q = 0; q <= nodeArray[x].length; q++) {
divs[x][q] = nodeArray[x][q][0];
};
};

Related

how to fill in the value in the array

i have code like this in actionscript3,
var map: Array = [
[[0,1,0],[0,1,0]],
[[0,1,0], [0,1,0]]];
var nom1: int = 0;
var nom2: int = 0;
var nom3: int = 1;
var nom4: int = 18;
stage.addEventListener (Event.ENTER_FRAME, beff);
function beff (e: Event): void
{
map[nom1][nom2][nom3] = nom4
}
stage.addEventListener (MouseEvent.CLICK, brut);
function brut(e: MouseEvent):void
{
trace (map)
}
when run, it gets an error in its output
what I want is to fill in each "1" value and not remove the "[" or "]" sign
so when var nom1, var nom2 are changed
Then the output is
[[[0,18,0],[0,18,0]],
[[0,18,0],[0,18,0]]]
please helps for those who can solve this problem
If what you want to achieve is to replace every 1 by 18 in this nested array, you could try :
for (var i = 0; i < map.length; i++) {
var secondLevel = map[i];
for (var j = 0; j < secondLevel.length; j++) {
var thirdLevel = secondLevel[j];
for (var k = 0; k < thirdLevel.length; k++) {
if (thirdLevel[k] === 1) {
thirdLevel[k] = 18;
}
}
}
}
Note that, this would only work for nested arrays with 3 levels of depth

SumProduct multi dimensional array using mathJS

I have some working code, which I wrote a while ago, where I created my own sumProduct functions, for performing this operation on singe and multi dimensional arrays:
function sumProduct1D(m1, m2) {
var result = 0;
var len = m1.length;
for (var i = 0; i < len; i++) {
result += m1[i] * m2[i];
}
return result;
}
function sumProduct2D(m1, m2) {
var result = 0;
var len1 = m1.length;
for (var i1 = 0; i1 < len1; i1++) {
var len2 = m1[i1].length;
for (var i2 = 0; i2 < len2; i2++) {
result += m1[i1][i2] * m2[i1][i2];
}
}
return result;
}
(These functions go through both arrays multiplying associated indexes and adding the total all together - in case you're not familiar with sumProduct).
At some point I started using mathJS for some of its matrix/array manipulation methods and I realised that my sumProduct1D is the same as math.dot
var a = [1,2,3];
var b = [3,2,1];
console.log(sumProduct1D(a,b));
console.log(math.dot(a,b));
function sumProduct1D(m1, m2) {
var result = 0;
var len = m1.length;
for (var i = 0; i < len; i++) {
result += m1[i] * m2[i];
}
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.8.0/math.js"></script>
The above code gives the same result for mine and using math.dot - perfect!
My question is around my other method - it sums a multidimensional array, and mathJS doesnt like it - I get an error Uncaught RangeError: Vector expected.
var c = [[1,2,3],[1,2,3]];
var d = [[3,2,1],[3,2,1]];
console.log(sumProduct2D(c,d))
console.log(math.dot(c,d))
function sumProduct2D(m1, m2) {
var result = 0;
var len1 = m1.length;
for (var i1 = 0; i1 < len1; i1++) {
var len2 = m1[i1].length;
for (var i2 = 0; i2 < len2; i2++) {
result += m1[i1][i2] * m2[i1][i2];
}
}
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.8.0/math.js"></script>
I have had a look through the mathJS docs, and I cannot for the life of me put together the combination of calls which duplicate my sumProduct2D. But there must be a way.
Can anyone replicate my sumProduct method using mathJS functions?
In case this helps anyone else, I found the answer eventually. It was math.sum(math.dotMultiply(c,d)) I was after.
var c = [[1,2,3],[1,2,3]];
var d = [[3,2,1],[3,2,1]];
console.log(sumProduct2D(c,d))
console.log(math.sum(math.dotMultiply(c,d)))
function sumProduct2D(m1, m2) {
var result = 0;
var len1 = m1.length;
for (var i1 = 0; i1 < len1; i1++) {
var len2 = m1[i1].length;
for (var i2 = 0; i2 < len2; i2++) {
result += m1[i1][i2] * m2[i1][i2];
}
}
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.8.0/math.js"></script>

I'm having trouble adding these elements of my array together. the dash seems to inhibit the addition of each variable

I'm trying to get the following code to add each number in the element separately and not the whole array together but the dash seems to stop the loop from calculating the total sum of each element. I can't seem to make it so it'll except any length of number for the variable. Any help is greatly appreciated!
var creditNum = [];
creditNum[0] = ('4916-2600-1804-0530');
creditNum[1] = ('4779-252888-3972');
creditNum[2] = ('4252-278893-7978');
creditNum[3] = ('4556-4242-9283-2260');
var allNum = [];
var total = 0;
var num = 0;
var cnt = 0;
for (var i = 0; i < creditNum.length; i++) {
num = creditNum[i];
for (var j = 1; j <= num.length; j++) {
var num = creditNum[i].substring(cnt, j);
console.log(creditNum[i].charAt(cnt));
console.log(cnt, j);
cnt = cnt + 1;
}
if (num != "-") j = j++;
console.log(parseInt(num));
}
console.log(total);
Assuming the intent is to add '4916-2600-1804-0530' and output the value as 49, then the following modification will achieve that.
var creditNum = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
for (var i = 0; i < creditNum.length; i++) {
var num = creditNum[i].replace(/\-/g, '');
var total = 0;
for (var j = 0; j < num.length; j++) {
total += Number(num[j]);
}
console.log(creditNum[i], total);
}
Using native array methods, the code can be refactored as the following.
var creditNumbers = ['4916-2600-1804-0530', '4779-252888-3972', '4252-278893-7978','4556-4242-9283-2260'];
creditNumbers.forEach(function(creditNumber) {
var num = creditNumber.replace(/\-/g, '').split('');
var total = num.reduce(function(tally, val) {
return tally += Number(val);
}, 0);
console.log(creditNumber, total);
});

Outputting new arrays

I am trying to produce an array by drawing data from two separate databases. I am getting close, but right now the data is output as one string: e.g.
[Smith, [ED-100,Some ClassED-200,Some Other Class]]
I would like the data to be in the form
[Smith, [[ED-100,Some Class], [ED-200,Some Other Class]]]
I have been spending hours fiddling with the code, but seem to have come up short. Here is what I have:
var teacherzCourses = [];
var teacherz = Object.getOwnPropertyNames(uniqTeach).sort();
for (var j = 0; j < teacherz.length; j++) {
var tName;
var tCourses = [];
for (k = 0; k < registrarData.length; k++) {
Object.getOwnPropertyNames(uniqTeach).sort();
// get the courses each teacher does
for (var j = 0; j < teacherz.length; j++) {
tName = teacherz[j];
tCourses = [];
tempArray = [];
for (k = 0; k < registrarData.length; k++) {
if (registrarData[k].Teacher.indexOf(teacherz[j]) > -1) {
console.log([teacherz[j], registrarData[k].CourseNum, registrarData[k].CourseName]);
tCourses += [registrarData[k].CourseNum, registrarData[k].CourseName];
};
tempArray += (tCourses);
};
teacherzCourses.push([tName, tCourses]);
};
};
console.table(teacherzCourses);
console.log(teacherzCourses[0][1]);
};
I have the feeling I am making this much more complicated than it needs to be.
Change this line:
tCourses += [registrarData[k].CourseNum, registrarData[k].CourseName];
to this:
tCourses.push([registrarData[k].CourseNum, registrarData[k].CourseName]);
As jfriend00 mentioned, there's no += operator on arrays.

Javascript create multidimensional array

I try to create a 4-dimensional array. I fill it dynamically and use content of it in another function. But the content is empty. Is there error below code?
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
I test below example :
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementByID('result').innerHTML = datas[0][0][0];
}
I see only ,,,,,,,.
I think the principal problem is that you're getting the element where you want to show your result badly using getElementByID instead of getElementById. Also make sure that your element has innerHTML property to write the result, or alternatively use value.
I write the follow example using <textArea id="result"></textArea> and generating a button which calls foo1();foo2(); onClick an it works for me.
In the sample I use an random value for timeInterval and allCoords.length.
Note also that you want a 4-dimensional array however you're creating a 3-dimensional.
var timeInterval = 60;
var allCoords = { length : 1};
var datas = []; // day number of a week
for(var i = 0; i < 7; i++) {
var size = 24*60/timeInterval;
datas[i] = [];
for(var j = 0; j < size; j++) {
var size2 = allCoords.length / 2;
datas[i][j] = [];
for(var k = 0; k < size2; k++) {
datas[i][j][k] = [];
}
}
}
function foo1()
{
datas[0][0][0].push(10);
}
function foo2()
{
document.getElementById('result').value = datas[0][0][0];
}
<textArea id="result"></textArea>
<input type="button" value="foo" onclick="foo1();foo2();"/>
Hope this helps,

Categories