How to use the map method In Javascript

In this approach, we are using the inbuilt ‘map‘ method to create a new output matrix by substracting the input matrices. Here, the code can perform the substraction of any number of the matrices.

Syntax:

map((element, index, array) => { /* … */ })

Example: In this example, we will be performing the subtraction of matrices in JavaScript by using the map method.

Javascript




function matSubUsingMap(inputMat) {
    if (inputMat.length < 2) {
  
        // We are checking length of
        // matrices are less than 2
        return null;
    }
  
    // Temporary we are intializing
    // result matrix with 1st matrix
    let resultMatrix = inputMat[0];
    for (
        let i = 1;
        i < inputMat.length;
        i++) {
        let currMat = inputMat[i];
        if (
            resultMatrix.length !==
            currMat.length ||
            resultMatrix[0].length !==
            currMat[0].length) {
            console.log("Not Possible")
            return null;
        }
        resultMatrix = resultMatrix.map(
            function (rowMat, i) {
                return rowMat.map(
                    function (
                        valueMat, j) {
                        return (
                            valueMat -
                            currMat[i][j]);
                    });
            });
    }
    return resultMatrix;
}
  
// All the Input Matrices are given here
let inputMatrix1 = [
    [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4],
];
let inputMatrix2 = [
    [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4],
];
let inputMatrix3 = [
    [1, 1, 1, 1],
    [2, 2, 2, 2],
    [3, 3, 3, 3],
    [4, 4, 4, 4],
];
  
// We are printing the output
let resultMatrix = matSubUsingMap([
    inputMatrix1,
    inputMatrix2,
    inputMatrix3,
]);
for (
    let i = 0;
    i < resultMatrix.length;
    i++) {
    console.log(
        resultMatrix[i].join(" "));
}


Output

-1 -1 -1 -1
-2 -2 -2 -2
-3 -3 -3 -3
-4 -4 -4 -4

JavaScript Program for Subtraction of Matrices

Subtraction of two matrices is a basic mathematical operation that is used to find the difference between the two matrices. In this article, we will see how we can perform the subtraction of input matrices using JavaScript.

Example:

Table of Content

  • Using Loop in JavaScript
  • Using the map method in JavaScript
  • Using the Array.from() method

Similar Reads

Using Loop in JavaScript

...

Using the map method in JavaScript

In this approach, we are using for loops to iterate over every individual element of the input matrices. This approach can perform the subtraction of any of the number of matrices, and then we are performing the subtraction of the response element and saving the result of the subtraction in the result matrix....

Using the Array.from() method

...