Return Largest Numbers in Arrays passed using reduce method?

To find the largest number in each array using the reduce() method, combine it with Math.max() and the spread operator. This approach processes multiple arrays and returns an array of maximum values.

Syntax

array.reduce((accumulator, currentArray) => {
    accumulator.push(Math.max(...currentArray));
    return accumulator;
}, []);

Example

const getBiggestNumberFromArraysPassed = allArrays => allArrays.reduce(
    (maxValue, maxCurrent) => {
        maxValue.push(Math.max(...maxCurrent));
        return maxValue;
    }, []
);

console.log(getBiggestNumberFromArraysPassed([[45, 78, 3, 1], [50, 34, 90, 89], [32, 10, 90, 99]]));
[ 78, 90, 99 ]

How It Works

The reduce() method iterates through each sub-array. For each array, Math.max(...currentArray) finds the maximum value using the spread operator to pass array elements as individual arguments. The result is pushed to the accumulator array.

Alternative Approach Using map()

const arrays = [[15, 25, 5], [100, 200, 50], [1, 3, 2]];

// Using map() method
const maxValues = arrays.map(arr => Math.max(...arr));
console.log(maxValues);
[ 25, 200, 3 ]

Comparison

Method Readability Use Case
reduce() More complex When you need more control over accumulation
map() Cleaner Simple transformation of each array

Conclusion

While reduce() works for finding maximum values in arrays, map() with Math.max() is often cleaner and more readable for this specific task. Choose reduce() when you need additional processing beyond simple transformation.

Updated on: 2026-03-15T23:18:59+05:30

207 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements