settingsAccountsettings
Menusettings

Q: Biggest Element in JavaScript matrix

+2 votes

Write a function in JavaScript that finds the biggest element inside a matrix.

The input comes as array of arrays, containing number elements (2D matrix of numbers).

Examples:

Input:
[[20, 50, 10],
 [8, 33, 145]]

Output:
145


Input:
[[3, 5, 7, 12],
 [-1, 4, 33, 2],
 [8, 3, 0, 4]]

Output:
33

The output is the return value of your function.

Find the biggest element and return it.

asked in JavaScript category by user richard8502

1 Answer

+1 vote

Use Number.NEGATIVE_INFINITY; to start with:

function biggestElement(matrix) {

    let biggestNum = Number.NEGATIVE_INFINITY;
    matrix.forEach(
            row => row.forEach(
                col => biggestNum = Math.max(biggestNum, col)));
    console.log(biggestNum);
}


biggestElement([
        [3, 5, 7, 12],
        [-1, 4, 33, 2],
        [8, 3, 0, 4]
    ]
);
answered by user nikole
...