I am facing a challenge with this issue concerning 2D arrays. The task at hand is to create a JavaScript function called addArrays(al, a2) that accepts two 2D arrays of numbers, a1 and a2, and calculates their "sum" following the matrix sum concept. In other words, if 'a' is an array containing the sum, then, for all rows 'i' and all columns 'j', a[i][j] = a1[i][j] + a2[i][j].
I am puzzled as I believe my logic for finding the sum is correct, but I'm unsure whether anything gets stored in the sum array or what this error message signifies. Any assistance would be highly appreciated.
This is the code snippet I have currently:
var sum = new Array(a1.length);
for (var k = 0; k<sum.length; k++) {
sum[k] = new Array(sum.length);
}
for (var l = 0; l<sum.length; l++) {
for (var m = 0; m<sum.length[l]; m++) {
sum[l][m].push(a1[l][m] + a2[l][m]);
}
}
return sum;
We are provided with a test script:
function start() {
var ar1 = [[1,2], [3,4]],
ar11 = [[1,2], [3,4], [5,6]],
ar12 = [[1,2,3], [3,4]],
ar2 = [[6,7], [8,9]],
ar21 = [[6,7], [8,9], [19,11]],
ar22 = [[6,7], [8,9,10]],
ar;
try {
alert( addArrays(ar1, ar2).toSource() );
}
catch (e) {
alert( e );
}}
Every time I execute the program, it keeps throwing the error: TypeError: addArrays(...).toSource is not a function