combine two 2D arrays in JavaScript

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

Answer №1

error: TypeError: addArrays(...).toSource is not a function

Indicates that the function toSource cannot be found in the result of calling addArrays. The use of Object.toSource is discouraged as it is non-standard.

As stated on MDN:

Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The output of toSource looks similar to JSON. It is recommended to consider using JSON.stringify for a similar outcome.

 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( JSON.stringify(addArrays(ar1, ar2)) );
  }
  catch (e) {
      alert( e );
  }}

Answer №2

To easily add two matrices of the same size, you can create a custom Array method called Array.prototype.matriceSum() like this:

Array.prototype.matriceSum = function(a) {
  return this.reduce((p,c,i) => (p[i] = c.reduce((f,s,j) => (f[j]+= s,f),p[i]),p),a.slice());
};
var matrix1 = [[1,2,3],[2,2,2],[4,5,6]],
    matrix2 = [[6,6,6],[9,8,7],[6,5,4]];
    resultMatrix = matrix1.matriceSum(matrix2);
console.log(JSON.stringify(resultMatrix));

This method does not modify the original array and instead returns a new 2D array with the sum of the two input matrices.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a method available to retrieve the data values stored within these objects?

Looking at the image below, I have data that includes a Data array in JSON format. The Data array contains key values such as condition_type and other related values. In order to extract individual values, I am using the following code: const submitcode ...

I have to arrange the results that I retrieve from MySQL in a specific order

Looking at the structure of my database table: id | igroup | title | url | text 1 | gr1 | Title 1 | urltoimage1 | text1 2 | gr1 | Title 2 | urltoimage2 | text2 3 | gr2 | Title 3 | urltoimage3 | text3 4 | gr2 | Title 4 ...

Using TypeScript to type styled-system props

Currently, I am utilizing styled-system and one of the main features of this library is its shorthand props that allow for simple and quick theming. Although I have streamlined my component, a significant aspect lies here: import React from 'react&a ...

Ways to transform an Array into an object

I had the idea to create a personalized dictionary for customers by utilizing the reduce function. Currently, I am achieving this using the forEach method. const customers = [ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: ' ...

I am experiencing issues with my JSON array when trying to integrate it into the Ionic framework with Cordova

I have successfully retrieved a JSON array from a URL in my Ionic app, but I am facing issues displaying it in a list. Here is the code snippet: home.ts file import { Component } from '@angular/core'; import { NavController } from 'ionic- ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

What is the best way to redefine an array within a loop while changing its size each time?

Currently, I am tackling a graph coloring problem that involves inputting the number of test cases in which the code needs to be executed. Here's the snippet of the code: #include <bits/stdc++.h> using namespace std; int main() { int test ...

What is the process for integrating an autoplay script into Turn.Js?

Can someone guide me on how to implement this code in Turn.Js? setInterval(function() { $('#flipbook').turn('next'); }, 1000); ...

ReactJS not displaying the class effect as intended

When using the react zoom pan pinch library, I am trying to set the height to "100%" for TransformWrapper and TransformComponent. Interestingly, it works perfectly fine when done through Chrome inspect, but when attempting to add a className or use style={ ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Having trouble with running `npm start` on a computer that has different versions of Node and

I have encountered an issue with running a React application on two different computers. One computer, a MacBook, is running the app without any problems, while the other, an Ubuntu 18.04 machine, is having trouble starting it. Here are the configurations ...

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

Dragging a Google Maps marker causes a border to appear around a nearby marker

Recently, I added a main draggable marker to the map. However, an unusual issue arises when dragging this marker - a blue outline appears around one of the existing markers on the map. This behavior is puzzling as it seems to be triggered by a click event ...

What is the appropriate way to notify Gulp when a task has been completed?

I have been working on developing a gulp plugin that counts the number of files in the stream. Taking inspiration from a helpful thread on Stack Overflow (source), I started implementing the following code: function count() { var count = 0; function ...

Tips for inserting a php variable into an html document

I am trying to figure out how to export a variable from a php file into an html file. The php file I'm working with is example.php and it contains the following code: <?php $array= ['one','two']; ?> The html file is named ...

When the page is refreshed, reorienting axes in three.js encounters difficulties

I am currently working on a project that involves using the three.js editor source code available for download on the three.js website. As part of this project, I am required to adjust the orientation of the axes to align with standard airplane coordinate ...

Monitoring variables in different AngularJS controllers

I have a component named histogram demo which includes a distinct controller with a variable known as $scope.selectedElements. I aim to monitor this variable in the primary appCtrl controller. How can I achieve access to this variable without using $rootSc ...

What is the best way to showcase content using Chakra-ui SideBar in a React Application?

After exporting the SideBar, I imported it into my App.jsx SideBar.jsx 'use client' import { IconButton, Avatar, Box, CloseButton, Flex, HStack, VStack, Icon, useColorModeValue, Text, Drawer, Draw ...

What is the most effective way to compare a nested array using the map or filter function in order to return only the first match

Here is a code snippet showcasing the data object containing information for the codeworks array with code and text values. There is a key array named code = ["ABC","MDH"] and the expected output is displayed in the following code snippets. const data = ...