ArticleZip > How To Find The Max Min Of A Nested Array In Javascript

How To Find The Max Min Of A Nested Array In Javascript

When working with arrays in JavaScript, it's common to encounter nested arrays. These nested arrays can contain multiple levels of data, making it challenging to find the maximum and minimum values within them. In this article, we'll explore a straightforward approach to finding the maximum and minimum values of a nested array in JavaScript.

To begin, let's consider a nested array that looks like this:

Javascript

const nestedArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

Our goal is to find both the maximum and minimum values within this structure. One way to achieve this is by using a simple loop to iterate through the nested arrays and compare each element with the current maximum and minimum values.

Here's a basic implementation of a function that can find the maximum and minimum values of a nested array:

Javascript

function findMaxMinNestedArray(nestedArray) {
    let max = Number.MIN_SAFE_INTEGER;
    let min = Number.MAX_SAFE_INTEGER;

    for (let i = 0; i < nestedArray.length; i++) {
        for (let j = 0; j  max) {
                max = nestedArray[i][j];
            }
            if (nestedArray[i][j]  max) {
            max = element;
        }
        if (element < min) {
            min = element;
        }
    }

    return { max, min };
}

const { maxRecursive, minRecursive } = findMaxMinNestedArrayRecursive(nestedArray);
console.log(`The maximum value (recursive) is: ${maxRecursive}`);
console.log(`The minimum value (recursive) is: ${minRecursive}`);

This recursive function can handle nested arrays with varying depths by recursively traversing through each element until it finds the maximum and minimum values.

By using these methods, you can efficiently find the maximum and minimum values of nested arrays in JavaScript, regardless of their complexity. Experiment with different nested array structures to see how these functions perform in various scenarios.