How to calculate the median of a matrix in JavaScript

1 Answer

0 votes
function findMedianUnsortedMatrix(matrix) {
    const elements = [];

    // Flatten the matrix
    for (const row of matrix) {
        for (const val of row) {
            elements.push(val);
        }
    }

    // Sort the elements
    elements.sort((a, b) => a - b);

    // Calculate median
    const n = elements.length;
    if (n % 2 === 1) {
        // Odd number of elements: return middle element
        return elements[Math.floor(n / 2)];
    } else {
        // Even number of elements: return average of two middle elements
        return (elements[n / 2 - 1] + elements[n / 2]) / 2.0;
    }
}

const matrix = [
    [5, 8, 9, 10],
    [1, 4, 6, 13],
    [7, 3, 0, 18],
    [6, 8, 9, 20]
];

const median = findMedianUnsortedMatrix(matrix);
console.log(`Median of the matrix is: ${median.toFixed(1)}`);


/*
run:

Median of the matrix is: 7.5

*/

 



answered 3 days ago by avibootz
edited 3 days ago by avibootz
...