Let say we have an array of object which and object contain age and name. Now we want to find out youngest person and elder person. For these we have to perform some logic to get right answer. Let do it.
Our array will look like this.
const users = [ {name: 'A', age: 12}, {name: 'B', age: 32}, {name: 'C', age: 30}, {name: 'D', age: 29}, ];
With this array, we want to find the highest and the lowest age users. But not only return the age but the whole object. We will use reduce method to achieve the result.
Find max from array of object
let max = users.reduce((previous, current) => { return previous.age > current.age ? previous : current; }); console.log(max); // { name: 'B', age: 32 }
Find min from array of array of object
let min = users.reduce((previous, current) => { return previous.age < current.age ? previous : current; }); console.log(min); // { name: 'A', age: 12 }