In JavaScript, the reduce() method is used to reduce an array to a single value. It is a powerful tool that can be used to solve various problems, including finding the two maximum values from an array.
const arr = [10, 20, 30, 40, 50];
const [max1, max2] = arr.reduce(([first, second], current) => {
if (current > first) {
second = first;
first = current;
} else if (current > second) {
second = current;
}
return [first, second];
}, [-Infinity, -Infinity]);
console.log(max1); // Output: 50
console.log(max2); // Output: 40
Here, we're using destructuring assignment to extract the first two values returned by reduce into max1 and max2. We start by initializing the accumulator to [-Infinity, -Infinity], which will be used to track the two largest numbers. We then iterate over the array, comparing each value to the two largest values found so far. If the current value is greater than the largest value, we shift the largest value to the second largest value, and set the largest value to the current value. If the current value is greater than the second largest value but less than or equal to the largest value, we set the second largest value to the current value. Finally, we return the updated accumulator, which contains the two largest values found in the array.
Top comments (0)