To get the two maximum values from an array of objects using the reduce() method in JavaScript, we can follow a similar approach to the one we used for the array of numbers. However, we need to modify the reducer function to account for the fact that we are working with objects instead of numbers.
Here's an example:
const arr = [ { name: 'John', age: 25 }, { name: 'Alice', age: 30 }, { name: 'Bob', age: 28 }, { name: 'Mary', age: 35 },];
const twoMaxValues = arr.sort((a, b) => b.age - a.age)
.reduce((acc, curr) => {
if (acc.length < 2) {
acc.push(curr);
} else if (curr.age > acc[1].age) {
acc[0] = acc[1];
acc[1] = curr;
} else if (curr.age > acc[0].age) {
acc[0] = curr;
}
return acc;
}, []);
console.log(twoMaxValues); // [{ name: 'Mary', age: 35 }, { name: 'Alice', age: 30 }]
We start by sorting the array in descending order based on the age property of the objects using the sort() method with a comparison function that subtracts b.age from a.age.
Next, we use the reduce() method to iterate over the sorted array. As before, we start with an empty array ([]) as the initial value for the accumulator (acc).
Inside the reducer function, we first check if the accumulator has less than two values. If so, we simply push the current object to the accumulator array.
If the accumulator already has two values, we compare the age property of the current object to the age properties of the objects in the accumulator. If the current object has a higher age than the second highest object in the accumulator (acc[1]), we replace acc[1] with the current object, and move the previous second highest object to the first position (acc[0] = acc[1]).
Finally, if the current object has a higher age than the first object in the accumulator (acc[0]), we replace it with the current object.
The reduce() method will return an array with the two objects with the highest age properties, which are the two objects with the highest ages in the original array of objects.
In the example above, the two objects with the highest ages are { name: 'Mary', age: 35 } and { name: 'Alice', age: 30 }, which are returned as the twoMaxValues array.
Thanks
Top comments (0)