find the lower triangular matrix in javascript

Here's a simple approach to find the lower triangular matrix of a given matrix in JavaScript using nested loops:

index.tsx
// Define the matrix
const matrix = [
  [1, 0, 0, 0],
  [2, 3, 0, 0],
  [4, 5, 6, 0],
  [7, 8, 9, 10]
];

// Get the number of rows/columns in the matrix
const n = matrix.length;

// Initialize an empty lower triangular matrix
const lowerTriangularMatrix = [];

// Loop through each row of the matrix
for (let i = 0; i < n; i++) {
  // Initialize an empty row for the lower triangular matrix
  const row = [];
  
  // Loop through each column of the matrix
  for (let j = 0; j < n; j++) {
    // If we're on or above the diagonal, the value is zero
    if (i < j) {
      row.push(0);
    }
    // Otherwise, copy the value from the original matrix
    else {
      row.push(matrix[i][j]);
    }
  }
  
  // Add the row to the lowerTriangularMatrix
  lowerTriangularMatrix.push(row);
}

// Print the lower triangular matrix
console.log(lowerTriangularMatrix);
860 chars
38 lines

This will output the following lower triangular matrix:

index.tsx
[
  [1, 0, 0, 0],
  [2, 3, 0, 0],
  [4, 5, 6, 0],
  [7, 8, 9, 10]
]
68 chars
7 lines

gistlibby LogSnag