How to usemap() method in Javascript
In this approach, we are using the inbuilt ‘map‘ method to create a new output matrix by adding the input matrices. Here, the code can perform the addition of two matrices in JavaScript.
Syntax:
map((element, index, array) => { /* … */ })
Example: In this example, we will be performing the Addition of two Matrices in JavaScript by using map method.
Javascript
let mat1 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]; let mat2 = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4], ]; let resmat = mat1.map((r, i) => r.map((v, j) => v + mat2[i][j]) ); for (let i = 0; i < resmat.length; i++) { console.log(resmat[i].join( ' ' )); } |
Output
2 2 2 2 4 4 4 4 6 6 6 6 8 8 8 8
JavaScript Program to Add Two Matrices
Given two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices
In this article, we will see how we can perform the addition of two input matrices using JavaScript.
Example:
Table of Content
- Using Loop in JavaScript
- Using map method
- Using the Array.from() method
Contact Us