You can find the minimum and maximum values in an array using the JavaScript reduce
function by iterating through the array and keeping track of the minimum and maximum values encountered.
reduce
function: Iterates through each element of the array, maintaining an accumulator (acc
) which, in this case, is an object that holds both the minimum and maximum values.
Here's how you can do it:
Example:
----------------------------------------------------------------------
const numbers = [3, 5, 1, 8, 2, 10];
const result = numbers.reduce((acc, current) => {
return {
min: current < acc.min ? current : acc.min,
max: current > acc.max ? current : acc.max
};
}, { min: Infinity, max: -Infinity });
console.log(`Min: ${result.min}, Max: ${result.max}`);
----------------------------------------------------------------------
No comments:
Post a Comment