Search code examples
javascriptmathmultidimensional-arrayarithmetic-expressionsmathjs

Element-Wise Arithmetic Operations in Jagged Multidimensional Arrays in JavaScript


I want to perform some element-wise arithmetric or mathematical operations on 2D jagged-arrays without flattening the output array; in this example, array C.

const A = [[1, 2, 30, 4],[5, 16, 7],[8, 9, 12, 14, 90]];
const B = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]];
const C = [];
for (let j = 0; j < A.length; j++) {
    for (let k = 0; k < A[j].length; k++) {
         C.push(0.5*A[j][k] + B[j][k]);
    }
}

console.log(C)

I have tried using a for loop but the output, C, is flattened. Also, I have used mathjs library function, but it seems the element-wise arithmetic operations in this library only works for non-jagged multidimensional arrays.


Solution

  • You could map the inner arrays and get a new arra of arrays with the wanted values.

    const
        a = [[1, 2, 30, 4],[5, 16, 7],[8, 9, 12, 14, 90]],
        b = [[45, 60, 15, 35],[45, 55, 75],[12, 34, 80, 65, 90]],
        c = a.map((inner, i) => inner.map((v, j) => 0.5 * v + b[i][j]));
    
    console.log(c);
    .as-console-wrapper { max-height: 100% !important; top: 0; }