How can I dynamically return an object key in array.map()?
Currently, I am retrieving the maximum value from an array using a specific object key with the following code:
Math.max.apply(Math, class.map(function (o) { return o.Students; }));
In this code snippet, 'class' represents an array and 'Students' is the key of each object within the array.
However, every time I need to find the maximum value, I have to write out that entire code block. To streamline this process, I decided to create a common method like so:
getMaxValue(array: any[], obj: key) {
return Math.max.apply(Math, array.map(function (o) {
return o.key; // Here I intend to return student objects
}));
}
With this method, I can simply pass in an array and the desired key (e.g., 'students') to retrieve the maximum value whenever needed:
var maxOfStudents = getMaxValue(class, "Students");
My question now is how can I dynamically return the key from an object within array.map()? Is there a way to achieve this?